Home >Backend Development >Golang >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, the sync
package is provided to implement various synchronization primitives, including mutex locks. The sync.Mutex
type is the most basic mutex lock type, which implements mutually exclusive access to resources through two methods Lock
and Unlock
.
Let’s take a closer look at the use of sync.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 variable count
is first defined to record the value of the counter, and then a mutex of type sync.Mutex
is defined lockmutex
. In the increment
function, obtain the mutex lock by calling mutex.Lock()
to ensure that only one coroutine can enter the critical section to perform the count
operation, and then Call mutex.Unlock()
to release the mutex lock so that other coroutines can continue to compete for execution.
In the main
function, 10 coroutines are created through a loop, and each coroutine calls the increment
function to increment the counter value. In order to ensure that all coroutines are executed, we use the time.Sleep
function to make the main coroutine wait for 1 second.
Finally, we print out the value of the counter, and we can see that count: 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's sync.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!