首頁  >  文章  >  後端開發  >  在繼續之前要求 Go 運行所有 goroutine

在繼續之前要求 Go 運行所有 goroutine

PHPz
PHPz轉載
2024-02-11 17:20:17870瀏覽

在继续之前要求 Go 运行所有 goroutine

在進行並發程式設計時,我們經常遇到需要等待所有goroutine完成後再繼續執行的情況。在Go語言中,我們可以透過使用WaitGroup來實現這個目標。 WaitGroup是一個計數信號量,可以用來等待一組goroutine的完成。在繼續之前,我們需要呼叫WaitGroup的Wait方法,這樣可以確保所有的goroutine都已經完成任務了。在本文中,我們將介紹如何正確使用WaitGroup來管理goroutine的執行順序。

問題內容

我需要 golang 調度程式在繼續之前執行所有 goroutine,runtime.gosched() 無法解決。

問題在於go 程式運行速度太快,以至於start() 中的「select」在stopstream() 內的「select」之後運行,然後「case <-chanstopstream:」接收器尚未準備好發件人「case retchan <-true:」。 結果是,當發生這種情況時,結果與 stopstream() 掛起時的行為相同

執行此程式碼https://go.dev/play/p/dq85xqju2q_z 很多時候你會看到這兩個回應 未掛起時的預期回應:

2009/11/10 23:00:00 start
2009/11/10 23:00:00 receive chan
2009/11/10 23:00:03 end

掛起時的預期回應,但掛起時的回應卻不是那麼快:

2009/11/10 23:00:00 start
2009/11/10 23:00:00 default
2009/11/10 23:00:01 timer
2009/11/10 23:00:04 end

程式碼

package main

import (
    "log"
    "runtime"
    "sync"
    "time"
)

var wg sync.WaitGroup

func main() {
    wg.Add(1)
    //run multiples routines on a huge system
    go start()
    wg.Wait()
}
func start() {
    log.Println("Start")
    chanStopStream := make(chan bool)
    go stopStream(chanStopStream)
    select {
    case <-chanStopStream:
        log.Println("receive chan")
    case <-time.After(time.Second): //if stopStream hangs do not wait more than 1 second
        log.Println("TIMER")
        //call some crash alert
    }
    time.Sleep(3 * time.Second)
    log.Println("end")
    wg.Done()
}

func stopStream(retChan chan bool) {
    //do some work that can be faster then caller or not
    runtime.Gosched()
    //time.Sleep(time.Microsecond) //better solution then runtime.Gosched()
    //time.Sleep(2 * time.Second) //simulate when this routine hangs more than 1 second
    select {
    case retChan <- true:
    default: //select/default is used because if the caller times out this routine will hangs forever
        log.Println("default")
    }
}

解決方法

在繼續執行當前 goroutine 之前,沒有辦法運行所有其他 goroutine。

透過確保 goroutine 不會在 stopstream 上阻塞來修復問題:

選項 1:將 chanstopstream 變更為緩衝通道。這確保了 stopstream 可以無阻塞地傳送值。

func start() {
    log.println("start")
    chanstopstream := make(chan bool, 1) // <--- buffered channel
    go stopstream(chanstopstream)
    ...
}

func stopstream(retchan chan bool) {
    ...
    // always send. no select/default needed.
    retchan <- true
}

https://www.php.cn/link/56e48d306028f2a6c2ebf677f7e8f800

選項 2:關閉通道而不是傳送值。通道始終可以由發送者關閉。在關閉的通道上接收返回通道值類型的零值。

func start() {
    log.Println("Start")
    chanStopStream := make(chan bool) // buffered channel not required
    go stopStream(chanStopStream)
    ...

func stopStream(retChan chan bool) {
    ...
    close(retChan)
}

https://www.php.cn/link/a1aa0c486fb1a7ddd47003884e1fc67f

#

以上是在繼續之前要求 Go 運行所有 goroutine的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除