You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
584 B
36 lines
584 B
package goConcurrency
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
)
|
|
|
|
func main() {
|
|
wg := sync.WaitGroup{}
|
|
// 计数器
|
|
counter := 0
|
|
// 多个goroutine并发的累加计数器
|
|
gs := 1000
|
|
wg.Add(gs)
|
|
lck := sync.Mutex{}
|
|
for i := 0; i < gs; i++ {
|
|
go func() {
|
|
defer wg.Done()
|
|
// 累加
|
|
for k := 0; k < 100; k++ {
|
|
lck.Lock()
|
|
counter++
|
|
lck.Unlock()
|
|
// ++ 操作不是原子的
|
|
// counter = counter + 1
|
|
// 1. 获取当前的counter变量
|
|
// 2. +1
|
|
// 3. 赋值新值到counter
|
|
}
|
|
}()
|
|
}
|
|
// 统计计数结果
|
|
wg.Wait()
|
|
fmt.Println("Counter:", counter)
|
|
}
|