This is a creation in Article, where the information may have evolved or changed.
Go mutex is a mutex, only lock and unlock two methods, the code between these two methods cannot be called simultaneously by multiple goroutins.
Look at the code:
Package main import ("FMT" "Sync" "Time") var m *sync. Mutex Func Main () {m = new (sync. Mutex) go lockprint (1) lockprint (2) time. Sleep (time. Second) fmt. Printf ("%s\n", "exit!")} Func lockprint (i int) {println (i, "lock start") M.lock () println (i, "in lock") time. Sleep (3 * time. Second) M.unlock () println (i, "Unlock")}
Interpretation:
The main function calls two times the Lockprint method, the println (i, "in lock") of this method, because it is between the lock and unlock of the mutex, so it is not possible to be executed again until the first call is not unlock.
Results:
2 Lock Start
2 in Lock
1 lock start
2 unlock
1 in lock
exit!
As can be seen from the above: after the second row of 2 in lock printing, 1 lock start has entered the call, but until 2 unlock after 1 in lock.
Ensures that the code between lock and unlock cannot be called simultaneously.