Home Backend Development Golang Does go language support locks?

Does go language support locks?

Dec 06, 2022 pm 06:32 PM
go golang go language

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
}
Copy after login

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())
}
Copy after login

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
Copy after login

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
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? Apr 02, 2025 pm 02:15 PM

Automatic deletion of Golang generic function type constraints in VSCode Users may encounter a strange problem when writing Golang code using VSCode. when...

See all articles