Goroutine与Mutex的同步

huangapple go评论70阅读模式
英文:

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 &lt; 100000; i++ {
		go func() {
			mutex.Lock()
			defer mutex.Unlock()
			atomic.AddInt32(&amp;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 (
    	&quot;fmt&quot;
    	&quot;sync&quot;
    	&quot;sync/atomic&quot;
    	&quot;time&quot;
    )
    
    func main() {
    	var n int32 = 0
    	var mutex *sync.Mutex = new(sync.Mutex)
    
    	for i := 0; i &lt; 100000; i++ {
    		go func() {
    			mutex.Lock()
    			defer mutex.Unlock()
    			atomic.AddInt32(&amp;n, 1)
    
    		}()
    	}
    	time.Sleep(5 * time.Millisecond)
    	fmt.Println(n)
    }
Output :
--------
100000

Or

package main

import (
	&quot;fmt&quot;
	&quot;sync&quot;
	&quot;sync/atomic&quot;
)

func main() {
	var n int32 = 0
	var mutex *sync.Mutex = new(sync.Mutex)
	var wg sync.WaitGroup

	for i := 0; i &lt; 100000; i++ {
		wg.Add(1)
		go func() {
			mutex.Lock()
			defer mutex.Unlock()
			atomic.AddInt32(&amp;n, 1)
			wg.Done()

		}()
	}
	wg.Wait()
	fmt.Println(n)
}

Output :
--------
100000

huangapple
  • 本文由 发表于 2022年9月22日 12:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/73809431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定