Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the main usage scenarios of locks in golang?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

What are the main scenarios involved in the use of locks in golang? For this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more small partners who want to solve this problem find simpler and easier ways.

1. What scene needs to be locked

When there is only one thread in the program, there is no need to add locks, but usually the actual code will not be just a single thread, there may be multiple threads accessing common resources at the same time, so this time you need to use locks, so what are the main use scenarios for locks?

1. When multiple threads read the same data

2. When multiple threads write the same data

3. The same resource, read and write time

Second, Go locks are divided into two types:

Mutex lock (sync.Mutex)

Read-write lock (sync.RWMutex depends on Mutex implementation)

Mutex locks are the most common way concurrent programs restrict access to common resources. In Go, sync.Mutex provides an implementation of mutex.

When a goroutine acquires a Mutex, other goroutines wait until the goroutine releases the Mutex.

Mutex structure:

type Mutex struct { state int32 sema uint32}

1. Lock status value is 1, unlock status lock is 0.

2. Lock() locks and unlocks.

Read/write lock is to lock the read/write operation. It should be noted that there is no mutual exclusion between multiple read operations, which improves the efficiency of accessing shared resources.

Read/write locks in Go are provided by sync.RWMutex, which blocks writes but not reads when read locks are occupied. RWMutex, in the case of a write lock, prevents any other goroutine (read or write) from entering, and the entire lock is equivalent to being owned exclusively by that goroutine.

Read-write lock structure:

type RWMutex struct { w Mutex // held if there are pending writers writerSem uint32 // semaphore for writers to wait for completing readers readerSem uint32 // semaphore for readers to wait for completing writers readerCount int32 // number of pending readers readerWait int32 // number of departing readers}

1. RWMutex is a single-write multiple-read lock, which can have multiple read locks or a single write lock.

2. Read lock occupancy prevents writing, not reading, and multiple goroutines can acquire read locks simultaneously.

3. The write lock prevents other gorotines from being read or written in, and the entire lock is occupied by the write lock goroutine.

4. Suitable for reading more and writing less scenes

3. How to use mutex

Mutex is a mutex lock, Lock() locks, Unlock() unlocks, after using Lock() to lock, it cannot be locked again, until using Unlock() to unlock it, it can be locked again. It is suitable for reading and writing uncertain scenarios, that is, there is no obvious difference between the number of reads and writes, and only one read or write is allowed, so the lock leaf is called a global lock.

A mutex lock can only be locked once. If it is locked again before unlocking, it cannot be locked. If the lock is unlocked before it is locked, the error "panic: sync: unlock of unlocked mutex" will be reported.

package mainimport ("fmt" "sync")

var ( count int lock sync.Mutex)

func main() { for i := 0; i

< 2; i++ { go func() { for i := 1000000; i >

0; i-- { lock.Lock() count ++ lock.Unlock() } fmt.Println(count) }() }

fmt.Scanf("\n") //Wait for all child threads to finish}

Run result: 1952533200000//Last thread printout

For the above program, a as a public resource, so the change of a, read and write operations need to be locked.

Issues to be noted:

1. Do not lock mutex repeatedly

2. Don't forget to unlock mutex, use defer statement if necessary

3. Do not pass mutex directly between multiple functions

4. How to use read-write locks

The scenario of read-write lock is mainly under multi-threaded safe operation, and the case of reading is more than that of writing, that is to say, both to meet the security of multi-threaded operation and to ensure that the performance is not too bad. At this time, we can consider using read-write lock. Of course, you can also use mutex simply and violently.

Lock() write lock, if there are other read locks and write locks before adding the write lock, lock blocks until the lock is available, to ensure that the lock is eventually available, blocked Lock calls exclude new readers from the acquired lock, i.e. write lock permissions are higher than read locks, write locks are preferred when there are write locks.

Unlock() The write lock unlocks, causing a runtime error if the write lock is not applied.

RLock() read lock, when there is a write lock, can not load the read lock, when only read lock or no lock, can load the read lock, read lock can load more, so it is suitable for "read more write less" scenario.

RUnlock() unlocks the read lock, and RUnlock undoes a single call to RLock, which has no effect on other simultaneous readers. If rw is not locked for reading, calling RUnlock raises a runtime error.

package mainimport ("fmt" "sync")

var ( count int rwLock sync.RWMutex)

func main() { for i := 0; i

< 2; i++ { go func() { for i := 1000000; i >

0; i-- { rwLock.Lock() count ++ rwLock.Unlock() } fmt.Println(count) }() }

fmt.Scanf("\n") //Wait for all child threads to finish}

Run Results: 19686372000000

It looks complicated, but in fact, it is simple:

Read lock cannot block read lock

Read locks need to block write locks until all read locks are released

Write locks need to block read locks until all write locks are released

Write locks need to block write locks

About golang lock use scenarios mainly involved in what questions the answer to share here, I hope the above content can be of some help to everyone, if you still have a lot of doubts not solved, you can pay attention to the industry information channel to learn more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 205

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report