栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 面试经验 > 面试问答

使用通道同步多个goroutine

面试问答 更新时间:发布时间: 百科书网 趣学号

使用sync.WaitGroup等待goroutine完成。关闭通道以使通道上的循环读取退出。

package mainimport (    "fmt"    "sync")type workerChannel chan uint64const num_workers = 5func main() {    results := make(chan string)    workCh := make(workerChannel)    // Start workers    var wg sync.WaitGroup    wg.Add(num_workers)    for i := 0; i < num_workers; i++ {        go func(num int) { defer wg.Done() // Loop processing work until workCh is closed for w := range workCh {     results <- fmt.Sprintf("worker %d, task %d", num, w) }        }(i)    }    // Close result channel when workers are done    go func() {        wg.Wait()        close(results)    }()    // Send work to be done    go func() {        for i := 0; i < 21; i++ { workCh <- uint64(i)        }        // Closing the channel causes workers to break out of loop        close(workCh)    }()    // Process results. Loop exits when result channel is closed.    for r := range results {        fmt.Println(r)    }}

https://play.golang.org/p/ZifpzsP6fNv



转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/417789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号