golang线程同步WaitGroup简介
2017-03-14 18:00
525 查看
WaitGroup用于线程同步,WaitGroup等待一组线程集合完成,才会继续向下执行。 主线程(goroutine)调用Add来设置等待的线程(goroutine)数量。 然后每个线程(goroutine)运行,并在完成后调用Done。 同时,Wait用来阻塞,直到所有线程(goroutine)完成才会向下执行。
对官方的代码做简单修改:
package main
import (
"fmt"
"sync"
)
func main() {
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)
go func(url string) {
// Launch a goroutine to fetch the URL.
defer wg.Done()
// Fetch the URL.
fmt.Println(url)
}(url)
}
// Wait for all goroutines to finish.
wg.Wait()
fmt.Println("Game Over")
}
执行结果为: http://www.somestupidname.com/ http://www.golang.org/ http://www.google.com/ Game Over可以看出3个线程(goroutine)全部执行完成后,wg.Wait()才停止等待,程序继续往下执行,输出Game Over。
对官方的代码做简单修改:
package main
import (
"fmt"
"sync"
)
func main() {
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)
go func(url string) {
// Launch a goroutine to fetch the URL.
defer wg.Done()
// Fetch the URL.
fmt.Println(url)
}(url)
}
// Wait for all goroutines to finish.
wg.Wait()
fmt.Println("Game Over")
}
执行结果为: http://www.somestupidname.com/ http://www.golang.org/ http://www.google.com/ Game Over可以看出3个线程(goroutine)全部执行完成后,wg.Wait()才停止等待,程序继续往下执行,输出Game Over。
相关文章推荐
- golang-----golang sync.WaitGroup解决goroutine同步
- golang 的 sync.WaitGroup
- golang sync WaitGroup
- Golang中的sync.WaitGroup用法实例
- golang waitgroup 及 sync.Once 示例
- golang--sync.WaitGroup使用示例
- Golang 1.7.3 Context 简单用法.类似sync.WaitGroup
- golang中的sync.WaitGroup
- golang基础-WaitGroup、kafka消费者
- golang sync WaitGroup
- GO: golang sync WaitGroup
- golang中协程同步sync.waitGroup
- GOLANG sync.WaitGroup讲解
- GoLang WaitGroup使用
- golang sync WaitGroup
- golang基础-WaitGroup、kafka消费者
- golang sync WaitGroup
- golang sync.WaitGroup解决goroutine同步
- golang sync.WaitGroup
- golang sync.WaitGroup解决goroutine同步