1 回答

TA貢獻1842條經驗 獲得超13個贊
vegeta 也會Attack立即返回,但通道中填充有仍在運行的 goroutine。一旦這些完成,通道就會關閉(defer close(results)),從而啟用必須檢測完成的代碼result。
例子;
package main
import (
"fmt"
"sync"
"time"
)
func main() {
results := attacks()
fmt.Println("attacks returned")
for result := range results {
fmt.Println(result)
}
}
func attacks() chan string {
// A channel to hold the results
c := make(chan string)
// Fire 10 routines populating the channel
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
attack(c)
wg.Done()
}()
}
// Close channel once routines are finished
go func() {
wg.Wait()
close(c)
}()
//
return c
}
func attack(c chan<- string) {
time.Sleep(1 * time.Second)
c <- "foobar"
}
- 1 回答
- 0 關注
- 151 瀏覽
添加回答
舉報