在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
示例代码: package main import ( "sync" "fmt" ) func doWorker(id int, ch chan int, wg *sync.WaitGroup) { for n := range ch { fmt.Printf("Worker %d received %c\n", id, n) wg.Done() // 减少一个计数 } } type worker struct { in chan int wg *sync.WaitGroup } func createWorker(id int, wg *sync.WaitGroup) worker { w := worker{ in: make(chan int), wg: wg, } go doWorker(id, w.in, wg) return w } func chanDemo() { var wg sync.WaitGroup var workers [10]worker for i:=0; i<10; i++ { workers[i] = createWorker(i, &wg) } for i, worker := range workers { wg.Add(1) // 添加一个计数 worker.in <- 'a' + i } wg.Wait() // 阻塞,等待所有任务完成 } func main() { chanDemo() }
// A Mutex is a mutual exclusion lock. 示例代码: package main import ( "sync" "fmt" ) var x = 0 func increment(wg *sync.WaitGroup, mu *sync.Mutex) { mu.Lock() x++ mu.Unlock() wg.Done() } func main() { var wg sync.WaitGroup var mu sync.Mutex for i := 0; i < 1000; i++ { wg.Add(1) go increment(&wg, &mu) } wg.Wait() fmt.Println("final value of x", x) }
// Do calls the function f if and only if Do is being called for the 示例代码: package main import ( "fmt" "sync" ) func One () { fmt.Println("One") } func Two() { fmt.Println("Two") } func main() { var once sync.Once for i, v := range make([]string, 10) { once.Do(One) fmt.Println("count:", v, "---", i) } } 执行结果: One count: --- 0 count: --- 1 count: --- 2 count: --- 3 count: --- 4 count: --- 5 count: --- 6 count: --- 7 count: --- 8 count: --- 9
|
请发表评论