1 回答
TA贡献1842条经验 获得超12个赞
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 关注
- 120 浏览
添加回答
举报