Principle and application analysis of locks in Golang
2.1 Mutex lock
The basic principle of mutex lock is to use a flag bit to indicate whether the resource is locked. When a goroutine wants to access a resource protected by a mutex, it will first try to acquire the lock. If the lock has been acquired by another goroutine, the current goroutine will be blocked until the lock is released. When a goroutine acquires the lock, it can operate on the resource and release the lock after completing the operation so that other goroutines can acquire the lock.
The following is an application example of a mutex lock:
package main import ( "fmt" "sync" ) var count int var lock sync.Mutex func increase() { for i := 0; i < 100000; i++ { lock.Lock() count++ lock.Unlock() } } func main() { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { increase() wg.Done() }() } wg.Wait() fmt.Println("count:", count) }
In the above example, we created a mutex lock lock
to protect the global variable count
read and write operations. Then 10 goroutines are started to operate the count
variable concurrently. Each goroutine will perform 100,000 addition operations on count
. Finally, output the value of count
, and we will find that the result is always 1000000, indicating that the mutex lock indeed guarantees the correctness of concurrent operations.
2.2 Read-write lock
Read-write lock is an extension of the mutex lock. It allows multiple goroutines to read shared resources at the same time, and ensures that there can only be one goroutine when writing resources. Read-write locks can improve the efficiency of concurrent processing of read operations.
The following is an application example of a read-write lock:
package main import ( "fmt" "sync" "time" ) var count int var rwlock sync.RWMutex func read() { rwlock.RLock() defer rwlock.RUnlock() fmt.Println("read:", count) } func write() { rwlock.Lock() defer rwlock.Unlock() count = count + 1 fmt.Println("write:", count) } func main() { go read() go write() time.Sleep(time.Second) }
In the above example, we created a read-write lock rwlock
to protect the global variable count
read and write operations. Two goroutines are started, one for reading and the other for writing. Since read operations can be performed at the same time, the read operations will be executed first, and the order of output read:
and write:
may be different. But we can ensure that the write operation is performed first, and then the read operation is performed to ensure the correctness of the data.
The above is the detailed content of In-depth analysis of the principles and applications of locks in Golang. For more information, please follow other related articles on the PHP Chinese website!