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.
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!

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor