GO 并发递增计数实例
所属分类 go
浏览量 866
两个版本 加锁和不加锁
不加锁的版本
count1.go
package main
import "fmt"
import "sync"
var count int
var NUM = 1000000
var GONUM = 100
var wg sync.WaitGroup
func main() {
wg.Add(GONUM)
for i := 0; i < GONUM; i++ {
go countadd()
}
wg.Wait()
fmt.Println(count)
}
func countadd(){
defer wg.Done()
for i := 0; i < NUM; i++ {
count++;
}
}
加锁的版本
count2.go
package main
import "fmt"
import "sync"
var count int
var NUM = 1000000
var GONUM = 100
var wg sync.WaitGroup
var lock sync.Mutex
func main() {
wg.Add(GONUM)
for i := 0; i < GONUM; i++ {
go countadd()
}
wg.Wait()
fmt.Println(count)
}
func countadd(){
defer wg.Done()
lock.Lock()
defer lock.Unlock()
for i := 0; i < NUM; i++ {
count++;
}
}
输出结果
go run count1.go
31019733
go run count1.go
30088065
go run count2.go
100000000
go run count2.go
100000000
完整代码
https://gitee.com/dyyx/hellocode/blob/master/web/tech/go/demo/count1.go
https://gitee.com/dyyx/hellocode/blob/master/web/tech/go/demo/count2.go
上一篇
下一篇
go select 与 定时器
go类型转换和断言
学习GO要了解的几个特性
Go并发构建模块
Go语言atomic原子操作
GO mutex 与 atomic 性能对比