WaitGroup的用途:它能够一直等到所有的goroutine执行完成,并且阻塞主线程的执行,直到所有的goroutine执行完成。
官方对它的说明如下:
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
sync.WaitGroup只有3个方法,Add(),Done(),Wait()。
其中Done()是Add(-1)的别名。简单的来说,使用Add()添加计数,Done()减掉一个计数,计数不为0, 阻塞Wait()的运行。
例子代码如下:
同时开三个协程去请求网页, 等三个请求都完成后才继续 Wait 之后的工作。
var wg sync.WaitGroup var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } for _, url := range urls { // Increment the WaitGroup counter. wg.Add(1) // Launch a goroutine to fetch the URL. go func(url string) { // Decrement the counter when the goroutine completes. defer wg.Done() // Fetch the URL. http.Get(url) }(url) } // Wait for all HTTP fetches to complete. wg.Wait()
或者下面的测试代码
用于测试 给chan发送 1千万次,并接受1千万次的性能。
package main import ( "fmt" "sync" "time" ) const ( num = 10000000 ) func main() { TestFunc("testchan", TestChan) } func TestFunc(name string, f func()) { st := time.Now().UnixNano() f() fmt.Printf("task %s cost %d \r\n", name, (time.Now().UnixNano()-st)/int64(time.Millisecond)) } func TestChan() { var wg sync.WaitGroup c := make(chan string) wg.Add(1) go func() { for _ = range c { } wg.Done() }() for i := 0; i < num; i++ { c <- "123" } close(c) wg.Wait() }
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 【爵士乐】VA-2024-SupremeLoungeChillSelectionJazzyVibeTunes(FLAC)
- 群星《承欢记 电视剧影视原声带》[FLAC/分轨][219.8MB]
- 群星《乘风2024 第1期》[320K/MP3][110.09MB]
- 群星《乘风2024 第1期》[FLAC/分轨][322.4MB]
- 【古典音乐】卡拉扬《莫扎特·魔笛(全剧)》2CD.2015[FLAC+CUE整轨]
- Yurika《ただいま》【Hi-Res】24bit-96kHz【flac】
- 张琍敏2006-金鼎奖系列14[台湾版]CD1[WAV+CUE]
- 林一峰2008-城市旅人[香港首版][WAV+CUE]
- 群星1990-六个梦电视原声带[日本版][WAV+CUE]
- [In-Akustik7801]KissedByASong-《Dynaudio丹拿发烧示范盘》(2014)HQCD[WAV+CUE]
- 群星《17号音乐仓库2 第10期》[320K/MP3][66.53MB]
- 群星《17号音乐仓库2 第10期》[FLAC/分轨][163.67MB]
- 宝丽金50周年《古典篇》3CD限定盘[低速原抓WAV+CUE][1.8G]
- 群星.1986-新格名曲精选-歌3【新格】【WAV+CUE】
- 【ABC唱片】徐刚《独步外滩SACD》ISO+WAV分轨