Golang 関数での goroutine の作成と管理

王林
リリース: 2024-06-05 19:06:01
オリジナル
1018 人が閲覧しました

Go 言語では、go キーワードと関数呼び出しを使用して goroutine を作成します。 goroutine を管理する場合は、同期に sync.WaitGroup を使用します。goroutine をキャンセルするには context パッケージを使用します。実際の戦闘では、ネットワークリクエストや画像処理などを並行して処理することができます。

Golang 函数中 goroutine 的创建和管理

Golang 関数でのゴルーチンの作成と管理

Goroutine (コルーチン) は、単一のスレッドで複数のタスクを同時に実行できる、Go 言語の軽量の並列実行ユニットです。

Goroutine の作成

goroutine の作成は非常に簡単です。 go キーワードの後に​​関数呼び出しを使用できます。 go 关键字后跟一个函数调用即可:

func hello() {
    fmt.Println("Hello from goroutine")
}

func main() {
    go hello() // 创建一个执行 hello() 函数的 goroutine
}
ログイン後にコピー

Goroutine 管理

同步

在处理共享资源时,需要对 goroutine 进行同步。使用 sync.WaitGroup 可以等待一组 goroutine 完成:

var wg sync.WaitGroup

func hello(name string) {
    wg.Add(1)
    defer wg.Done()

    fmt.Println("Hello", name)
}

func main() {
    wg.Add(3)
    go hello("John")
    go hello("Mary")
    go hello("Bob")
    wg.Wait() // 等待所有 goroutine 完成
}
ログイン後にコピー

取消

可以使用 context

import (
    "context"
    "fmt"
    "time"
)

func heavyComputation(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Computation cancelled")
            return
        default:
            // 执行计算
        }
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    go heavyComputation(ctx)
    time.Sleep(10 * time.Second) // 10 秒后取消计算
}
ログイン後にコピー

Goroutine 管理

同期

共有処理リソースの場合、ゴルーチンを同期する必要があります。 sync.WaitGroup を使用して goroutine のグループが完了するのを待ちます:

func main() {
    urls := []string{"https://example.com", "https://example.net", "https://example.org"}

    var wg sync.WaitGroup

    for _, url := range urls {
        wg.Add(1)
        go func(url string) {
            resp, err := http.Get(url)
            if err != nil {
                log.Fatal(err)
            }

            resp.Body.Close()
            wg.Done()
        }(url)
    }

    wg.Wait()
}
ログイン後にコピー

Cancel

context パッケージを使用して goroutine をキャンセルできます:
func main() {
    images := []string{"image1.jpg", "image2.jpg", "image3.jpg"}

    var wg sync.WaitGroup

    for _, image := range images {
        wg.Add(1)
        go func(image string) {
            img, err := image.Decode(image)
            if err != nil {
                log.Fatal(err)
            }

            // 处理图像

            wg.Done()
        }(image)
    }

    wg.Wait()
}
ログイン後にコピー
実践事例

ネットワークリクエストの並列処理:

🎜rrreee🎜🎜 画像処理の並列処理: 🎜🎜rrreee

以上がGolang 関数での goroutine の作成と管理の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!