[英]How to make multiple go routines wait for some output from another goroutine
Main {
go routine_1(carryout a time consuming task and return output)
go routine_2(wait for output from routine_1, collect output and do task_2)
go routine_3(wait for output from routine_1, collect output and do task_3)
wait for all routines to complete
}
我使用過通道,但是一旦routine_2 讀取數據routine_3 就沒有得到數據。
我不希望主線程進行同步,即知道routine_2、routine_3 到routine_1 之間的依賴關系
事實證明,關閉頻道將為其他例程提供所需的廣播,以了解結果已准備好。
謝謝你的時間。(這是我在stackoverflow的第一個問題,很高興看到這么好的質量和快速的回復)謝謝大家。
更新我選擇的答案。 再次感謝。
package main
import (
"fmt"
"sync"
)
func computeResult() int {
return 100
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
var output int
ch := make(chan struct{})
// Compute result
go func() {
defer wg.Done()
output = computeResult()
fmt.Println("closing channel to signal task done")
close(ch)
fmt.Println("channel closed")
}()
go func() {
defer wg.Done()
// Wait for ch close
<-ch
fmt.Println(output)
}()
wg.Wait()
var wg2 sync.WaitGroup
wg2.Add(1)
go func() {
defer wg2.Done()
fmt.Println("wait on closed channel")
// Wait for ch close
<-ch
fmt.Println(output)
}()
wg2.Wait()
}
您可以在第一個例程完成后調用其他兩個例程:
var wg sync.WaitGroup
wg.Add(2)
go func() {
output := task1()
go func() {
defer wg.done()
task2(output)
}
go func() {
defer wg.done()
task3(output)
}
}()
wg.Wait()
您可以使用關閉通道來廣播結果准備情況,並使用共享變量來存儲結果:
func() {
var output SomeType
ch:=make(chan struct{})
// Compute result
go func() {
output=computeResult()
close(ch)
}()
go func() {
// Wait for ch close
<-ch
useOutput()
}()
}
您可以有許多 goroutine 等待通道關閉。 當通道關閉時,所有的 goroutine 都將被啟用。
你可以這樣做...... - 創建任務,然后是結果 - 結果用作另一個任務.. - 使用等待組(prperty 同步包)主要用於等待功能...... - 使用 lamda function 和時間間隔(time.sleep(time. sec/min). - 這里基於任務依賴使用 Mutex(lock/unlock)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.