英文:
Goroutine synchronization with Mutex
问题
var n int32 = 0
var mutex *sync.Mutex = new(sync.Mutex)
for i := 0; i < 100000; i++ {
go func() {
mutex.Lock()
defer mutex.Unlock()
atomic.AddInt32(&n, 1)
}()
}
fmt.Println(n)
我想知道为什么 n
的结果不是 100000,看起来互斥锁没有起作用。
英文:
var n int32 = 0
var mutex *sync.Mutex = new(sync.Mutex)
for i := 0; i < 100000; i++ {
go func() {
mutex.Lock()
defer mutex.Unlock()
atomic.AddInt32(&n, 1)
}()
}
fmt.Println(n)
I'm wondering why the result of n
is not 100000, looks like the mutex lock does not work.
答案1
得分: 2
fmt.Println(n)在go线程完成之前执行,你需要在fmt.Println(n)之前添加time.Sleep(5 * time.Millisecond),如下所示:
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var n int32 = 0
var mutex *sync.Mutex = new(sync.Mutex)
for i := 0; i < 100000; i++ {
go func() {
mutex.Lock()
defer mutex.Unlock()
atomic.AddInt32(&n, 1)
}()
}
time.Sleep(5 * time.Millisecond)
fmt.Println(n)
}
输出:
100000
或者
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var n int32 = 0
var mutex *sync.Mutex = new(sync.Mutex)
var wg sync.WaitGroup
for i := 0; i < 100000; i++ {
wg.Add(1)
go func() {
mutex.Lock()
defer mutex.Unlock()
atomic.AddInt32(&n, 1)
wg.Done()
}()
}
wg.Wait()
fmt.Println(n)
}
输出:
--------
100000
英文:
fmt.Println(n) is executing before the go threads completion,You need to add the time.Sleep(5 * time.Millisecond) before fmt.Println(n) like below
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
var n int32 = 0
var mutex *sync.Mutex = new(sync.Mutex)
for i := 0; i < 100000; i++ {
go func() {
mutex.Lock()
defer mutex.Unlock()
atomic.AddInt32(&n, 1)
}()
}
time.Sleep(5 * time.Millisecond)
fmt.Println(n)
}
Output :
--------
100000
Or
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var n int32 = 0
var mutex *sync.Mutex = new(sync.Mutex)
var wg sync.WaitGroup
for i := 0; i < 100000; i++ {
wg.Add(1)
go func() {
mutex.Lock()
defer mutex.Unlock()
atomic.AddInt32(&n, 1)
wg.Done()
}()
}
wg.Wait()
fmt.Println(n)
}
Output :
--------
100000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论