critical section
var data int
go func() { data++}() ifdata==0{
fmt.Println("the value is 0.") }else{
fmt.Printf("the value is %v.\n", data)
}
- Our goroutine, which is incrementing the data variables.
- Our if statement, which checks whether the value of data is 0.
- Our fmt.Printf statement, which retrieves the value of data for output.
解决 critical section 的蠢办法
对的,就是加锁
var memoryAccess sync.Mutex var value int
go func() {
memoryAccess.Lock()
value++
memoryAccess.Unlock()
}()
memoryAccess.Lock()
if value==0 {
fmt.Printf("the value is %v.\n", value)
} else {
fmt.Printf("the value is %v.\n", value)
}
memoryAccess.Unlock()
这里只解决了 data race,但是没有实际的去解决 race condition。
上面的代码中,到底是 go func 先执行还是 if 判断语句先执行,是没有明确的。
Deadlock
type value struct {
mu sync.Mutex
value int
}
var wg sync.WaitGroup
printSum := func(v1, v2 *value) {
defer wg.Done() v1.mu.Lock()
defer v1.mu.Unlock()
time.Sleep(2*time.Second) v2.mu.Lock()
defer v2.mu.Unlock()
fmt.Printf("sum=%v\n", v1.value + v2.value)
}
var a, b value wg.Add(2)
go printSum(&a, &b) go printSum(&b, &a) wg.Wait()
网友评论