Home >Backend Development >Golang >When to use lock in golang

When to use lock in golang

(*-*)浩
(*-*)浩Original
2019-12-27 11:30:552838browse

When to use lock in golang

The sync package in the Go language package provides two lock types: sync.Mutex and sync.RWMutex.              (Recommended learning: go)

Mutex is the simplest type of lock, and it is also more violent. When a goroutine obtains Mutex, other goroutines can only behave. Wait until this 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 Preventing any other goroutine (regardless of reading and writing) from coming in, the entire lock is equivalent to being exclusively owned by this goroutine. From the implementation of RWMutex, the RWMutex type actually combines Mutex:

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

sync.mutex After locking, reading or writing in other places is prohibited. This applies to possible modifications to the same data in different go coroutines.

The use of lock and unlock in sync.rwmutex is similar to that of sync.mutex

The use of rlock and runlock of sync.rwmutex is suitable for reading data to prevent reading failure caused by writing in other places that may occur while reading.

The above is the detailed content of When to use lock in golang. 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