How to implement locking mechanism in Go language?
In the Go language, you can use the Mutex type from the sync package to implement a locking mechanism. Mutex is a mutual exclusion lock that can be used to protect critical sections and prevent multiple goroutines from accessing shared resources simultaneously.
The following is an example code using Mutex to implement locking mechanism:
package main
import (
"fmt"
"sync"
"time"
)
var (
count int
lock sync.Mutex
)
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go increment(&wg)
}
wg.Wait()
fmt.Println("Final count:", count)
}
func increment(wg *sync.WaitGroup) {
lock.Lock() // 加锁
defer lock.Unlock() // 解锁
defer wg.Done()
// 模拟耗时操作
time.Sleep(time.Millisecond * 100)
count++
}
In the above code, we first create a global variable count and a Mutex variable called lock. Then, in the increment function, we use the lock.Lock() method to lock the critical section, ensuring that only one goroutine can enter the critical section. Within the critical section, the count is incremented. Finally, we use the lock.Unlock() method to unlock the critical section.
Running the code above will produce the correct incrementing results and ensure that multiple goroutines do not access the critical section simultaneously, implementing a lock mechanism.