1. 用Mutex实现
package main import ( "fmt" "sync" ) var num int var mtx sync.Mutex var wg sync.WaitGroup func add() { mtx.Lock() defer mtx.Unlock() defer wg.Done() num += 1 } func main() { for i := 0; i < 100; i++ { wg.Add(1) go add() } wg.Wait() fmt.Println("num:", num) }
2. 使用chan实现
package main import ( "fmt" "sync" ) var num int func add(h chan int, wg *sync.WaitGroup) { defer wg.Done() h <- 1 num += 1 <-h } func main() { ch := make(chan int, 1) wg := &sync.WaitGroup{} for i := 0; i < 100; i++ { wg.Add(1) go add(ch, wg) } wg.Wait() fmt.Println("num:", num) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- @synchronized 互斥锁
- golang 互斥锁
- 自旋锁和互斥锁区别 --- 经典
- golang 互斥锁 sync.Mutex
- 互斥量与临界区的区别
- Golang学习笔记之互斥锁(Mutex)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Head First Rails
David Griffiths / O'Reilly Media / 2008-12-30 / USD 49.99
Figure its about time that you hop on the Ruby on Rails bandwagon? You've heard that it'll increase your productivity exponentially, and allow you to created full fledged web applications with minimal......一起来看看 《Head First Rails》 这本书的介绍吧!