Home>Article>Backend Development> Go language document analysis: sync.Mutex function implements mutex lock
Go language is an open source programming language that uses a concurrent programming model to handle the alternate execution of multiple tasks. In concurrent programming, it often involves multiple coroutines or threads accessing shared resources at the same time. In this case, a mutex lock needs to be used to ensure the exclusivity of the resource and avoid the occurrence of race conditions.
In the Go language, thesync
package is provided to implement various synchronization primitives, including mutex locks. Thesync.Mutex
type is the most basic mutex lock type, which implements mutually exclusive access to resources through two methodsLock
andUnlock
.
Let’s take a closer look at the use ofsync.Mutex
.
package main import ( "fmt" "sync" "time" ) var count int var mutex sync.Mutex func increment() { mutex.Lock() // 加锁 defer mutex.Unlock() // 解锁,在函数执行完毕后自动调用 count++ } func main() { for i := 0; i < 10; i++ { go increment() } time.Sleep(time.Second) // 等待所有协程执行完毕 fmt.Println("count:", count) }
In the above code, a global variablecount
is first defined to record the value of the counter, and then a mutex of typesync.Mutex
is defined lockmutex
. In theincrement
function, obtain the mutex lock by callingmutex.Lock()
to ensure that only one coroutine can enter the critical section to perform thecount
operation, and then Callmutex.Unlock()
to release the mutex lock so that other coroutines can continue to compete for execution.
In themain
function, 10 coroutines are created through a loop, and each coroutine calls theincrement
function to increment the counter value. In order to ensure that all coroutines are executed, we use thetime.Sleep
function to make the main coroutine wait for 1 second.
Finally, we print out the value of the counter, and we can see thatcount: 10
is correctly output.
Using mutex locks can ensure safe access to shared resources and avoid data races. It is very important to use mutex locks when multiple coroutines or threads access shared resources. Go language'ssync.Mutex
provides a simple and powerful mutex lock function, making concurrent programming easier and safer.
The above is the detailed content of Go language document analysis: sync.Mutex function implements mutex lock. For more information, please follow other related articles on the PHP Chinese website!