Mutex: Solve the problem of concurrent resource access?

Speaking of concurrent access issues, it is really common, such as multiple goroutines concurrently updating the same resource, such as a counter; updating user account information at the same time; killing the system in seconds; concurrently writing data to the same buffer, etc. If there is no mutual exclusion control, there will be some abnormal situations, such as inaccurate counting of the counter, possible overdraft of the user's account, overselling of the seckill system, confusion of data in the buffer, etc., and the consequences are very serious.
How to solve these problems? Yes, use a mutex, that is Mutex in the Go language.

I will take you to learn more about the implementation mechanism of the mutex, and the basic usage of the mutex Mutex in the Go standard library. In the following three lessons, I will also explain the specific implementation principle of Mutex, error-prone scenarios and some extended usage.
Well, let's take a look at the implementation mechanism of the mutex first.

Implementation mechanism of mutual exclusion lock

Mutex is a basic means of concurrency control and a concurrency control mechanism established to avoid competition. Before learning its specific implementation principles, we must first understand a concept, which is the critical section.
In concurrent programming, if part of the program will be accessed or modified concurrently, then, in order to avoid unexpected results caused by concurrent access, this part of the program needs to be protected. This part of the protected program is called a critical section .

It can be said that a critical section is a shared resource, or a whole set of shared resources, such as access to a database, operations on a shared data structure, use of an I/O device, and access to a connection. calls for pooled connections, and so on.

If many threads access the critical section synchronously, it will cause access or operation errors, which is of course not the result we want to see. Therefore, we can use a mutex to limit the critical section to only be held by one thread at a time.

When a critical section is held by a thread, if other threads try to enter this critical section, a failure will be returned.

Guess you like

Origin blog.csdn.net/guofeidageda/article/details/129954015