Home  >  Article  >  Backend Development  >  Does go language support locks?

Does go language support locks?

青灯夜游
青灯夜游Original
2022-12-06 18:32:225688browse

The go language supports locks. The go language standard library provides two types of locks: 1. Mutex lock (sync.Mutex), which can protect a resource from conflicts caused by concurrent operations and resulting in inaccurate data; 2. Read-write lock (sync.RWMutex), When the read lock is occupied, writing is blocked, but reading is not blocked. In an environment with more reads and less writes, read-write mutexes can be used first.

Does go language support locks?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

The go language standard library provides two locks, one is a mutual exclusion lock, and the other is a read-write lock. The sync package in the Go language package provides two lock types: mutex lock (sync.Mutex) and read-write lock (sync.RWMutex).

Mutex is the simplest type of lock, and it is also relatively violent. When a goroutine obtains a Mutex, other goroutines can only wait until the goroutine releases the Mutex.

RWMutex is relatively friendly and is a classic single-write-multiple-read model. When the read lock is occupied, writing will be blocked, but reading will not be blocked. That is, multiple goroutines can acquire the read lock at the same time (calling the RLock() method); while the write lock (calling the Lock() method) will prevent any other goroutine ( Regardless of whether reading or writing) comes in, the entire lock is equivalent to being exclusively owned by the goroutine. Judging from the implementation of RWMutex, the RWMutex type actually combines Mutex:

type RWMutex struct {
    w Mutex
    writerSem uint32
    readerSem uint32
    readerCount int32
    readerWait int32
}

For these two lock types, any Lock() or RLock() needs to ensure that there is a corresponding Unlock() or RUnlock() call and Otherwise, all goroutines waiting for the lock may be starved, or even deadlock. [Related recommendations: Go video tutorial, Programming teaching]

The typical usage pattern of the lock is as follows:

package main
import (
    "fmt"
    "sync"
)
var (
    // 逻辑中使用的某个变量
    count int
    // 与变量对应的使用互斥锁
    countGuard sync.Mutex
)
func GetCount() int {
    // 锁定
    countGuard.Lock()
    // 在函数退出时解除锁定
    defer countGuard.Unlock()
    return count
}
func SetCount(c int) {
    countGuard.Lock()
    count = c
    countGuard.Unlock()
}
func main() {
    // 可以进行并发安全的设置
    SetCount(1)
    // 可以进行并发安全的获取
    fmt.Println(GetCount())
}

The code description is as follows:

  • Line 10 is a variable used in a certain logical step, whether it is a package-level variable or a structure member field.

  • Line 13, under normal circumstances, it is recommended to set the granularity of the mutex lock as small as possible to reduce the waiting time for shared access. Here, the author habitually names the mutex variable in the following format:

变量名+Guard

to indicate that the mutex is used to protect this variable.

  • Line 16 is a function encapsulation to obtain the count value. Through this function, the variable count can be accessed concurrently and safely.

  • Line 19, try to lock the countGuard mutex. Once countGuard is locked, if another goroutine tries to continue locking, it will be blocked until countGuard is unlocked.

  • Line 22 uses defer to delay the unlocking call of countGuard. The unlocking operation will occur when the GetCount() function returns.

  • When setting the count value in line 27, countGuard is also used to perform locking and unlocking operations to ensure that the process of modifying the count value is an atomic process and no concurrent access conflicts will occur.

In an environment where there is a lot of reading and little writing, you can give priority to using a read-write mutex (sync.RWMutex), which is more efficient than a mutex. RWMutex in the sync package provides an encapsulation of read-write mutexes.

We modified part of the code in the mutex example to a read-write mutex, see the code below:

var (
    // 逻辑中使用的某个变量
    count int
    // 与变量对应的使用互斥锁
    countGuard sync.RWMutex
)
func GetCount() int {
    // 锁定
    countGuard.RLock()
    // 在函数退出时解除锁定
    defer countGuard.RUnlock()
    return count
}

The code description is as follows:

  • Line 6, when declaring countGuard, change the sync.Mutex mutex lock to the sync.RWMutex read-write mutex lock.

  • Line 12, the process of obtaining count is a process of reading count data, which is suitable for read and write mutex locks. In this line, replace countGuard.Lock() with countGuard.RLock() to mark the read-write mutex as read. If another goroutine concurrently accesses countGuard and calls countGuard.RLock() at the same time, no blocking will occur.

  • Line 15, corresponding to read mode locking, uses read mode to unlock.

Special note:

  • The lock of sync.Mutex cannot be nested

  • The RLock() of sync.RWMutex can be nested

  • The mu.Lock() of sync.RWMutex cannot be nested

  • mu.RLock() cannot be nested in mu.Lock() of sync.RWMutex

For more programming related knowledge, please visit:programming video! !

The above is the detailed content of Does go language support locks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn