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

Case Analysis of Mutex Lock and read-write Lock in Go language

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Most people do not understand the knowledge points of this article "Go language mutex lock and read-write lock example analysis", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Go language mutex lock and read-write lock case analysis" article.

Foreword:

In a single thread, there is only one thread to operate the data, and only one thread is involved in the modification of the data. the data is relatively safe, and there is more than one thread to operate on the data in the case of multiple threads. so it is hard to avoid confusion when modifying the data at the same time.

What is a mutex? 1. Concept

Mutex is for the security of concurrency. When multiple goroutine work together, it is very unsafe to write shared data. It is easy to cause unnecessary data loss due to competition. Mutexes are generally added to the places where shared data is modified.

two。 Unlocked

If the thread is not safe, the global variable of the operation will calculate the exception.

Package mainimport ("fmt"sync") var x int = 0var wg sync.WaitGroupfunc add () {defer wg.Done () for I: = 0; I < 5000 Func main () {wg.Add (2) go add () go add () wg.Wait () fmt.Println (x)} / * print the result: (each print is different, the normal result should be 10000) 6051 5059 5748 10000 printer 3. After adding the lock

Thread safety, no exception in global variable calculation

Package mainimport ("fmt"sync") var x int = 0var wg sync.WaitGroup// create a lock object var lock sync.Mutexfunc add () {defer wg.Done () for I: = 0; I < 5000 Lock.Lock + {/ / unlock lock.Unlock ()} func main () {wg.Add (2) / / Open two threads go add () go add () wg.Wait () fmt.Println (x)} / * print result: all 10000cycles / 2, read / write lock [efficiency Revolution] 1. Why is read-write lock efficient?

When using locks, security and efficiency often need to be transformed into each other, and when operating on the data, only the data will be read and written. While reading and reading can be carried out at the same time, between reading and writing, it is necessary to ensure that you do not read when you write. At this time, in order to improve the efficiency, the read-write lock is invented. Under the read-write lock mechanism, the security is not reduced at all, but the efficiency is improved exponentially, and the efficiency is more obvious when the difference between the number of read and write operations is greater.

two。 Usage

The code is as follows (example):

Package mainimport ("fmt"sync"time") var (x = 0 rwlock sync.RWMutex wg sync.WaitGroup) func write () {defer wg.Done () rwlock.Lock () rwlock.Unlock ()} func read () {wg.Done () / / Open the read lock rwlock.RLock () fmt.Println (x) / / release the read lock rwlock. RUnlock ()} func main () {start: = time.Now () for I: = 0 I < 100; iTunes + {wg.Add (1) go write ()} / / time.Sleep (time.Second) for I: = 0; I < 10000; iTunes + {wg.Add (1) go read ()} wg.Wait () fmt.Println () fmt.Println (time.Now (). Sub (start))} 3. Sync.once1.sync.once generation background

In multiple goroutine, data read and write conflicts are often caused by asynchronous threads, especially when creating file open objects, which may result in writing to closed files, using uninitialized objects, or initializing an object multiple times.

Overview of 2.sync.once Mechanism

Sync.once ensures that the code in the function is executed only once. The implementation mechanism is that there is a flag bit inside the once. After the code is executed once, the flag bit is set to 1 subsequent judgment flag bit. If the flag bit is changed to 1, it can no longer be manipulated.

3.sync.once, pay attention.

The function parameters passed in by sync.Once.Do () have no parameters and no return, and an once object can only execute the Do method once. When passing multiple different functions to the Do method, you can only execute the first function passed in, and the function passed into the Do method has no parameters and no return. You can use function closures to pass in the required variables.

4. Usage

It is generally used concurrently to close the channel or file only once.

Func f2 (a)

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: 0

*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

Development

Wechat

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

12
Report