Multi-thread synchronization of four ways

For multithreaded programs, the synchronization means within a certain period of time to allow only one thread to access a resource. And during this time, we do not allow other threads access the resource. By mutex (Mutex), the condition variable (condition variable), read-write lock (reader-writer lock), the semaphore (semaphore) to synchronize the resource.

 

1. mutex (the Mutex)

Mutex is the simplest synchronization mechanism that mutex. Multiple processes (threads) can access to a mutex, the mutex lock, so that a critical area to protect, prevent other processes (threads) simultaneously enters the critical zone, the protection of exclusive access to critical resources.

2. condition variable (condition variable)

Condition variable for multiple processes (threads) wait for the same event, and then buckle down to something. Take a simple example:

Producer and consumer models:
more consumers to wait for producers to produce goods that consumers to consume goods. When a producer produced an item, you can notify all consumers (of course, you can also inform consumers only one waiting) --- can go to consume the goods. Then more competition for consumer goods will go, who fast who can get the items consumed. If this product is consumed, consumers wait for the producer. This is similar to the scene.
Mutex condition variable must cooperate to work together. why? As producers of goods produced are critical resources, public resources, that is, all processes and threads can be used at a time only allows a consumer to pick up. Then they use a mutex to protect critical resources.

3. write lock (reader-writer lock)

Read-write lock suitable for use in a multi-read operation, a write operation of small, such as a database. Read-write lock lock can be added at the same time a lot, but write locks are mutually exclusive. When a process or thread to write, must wait for all of the reading process or thread to release their read locks party can write. Many times the database might just make some inquiries.

4. semaphore (semaphore)

In the producer-consumer model, the record for the number of tasks you can use a semaphore to do. It can be understood as the condition variable band counted. When the value of the semaphore is less than 0, the work process or thread is blocked waiting for the arrival of goods. When producers to produce an item, the magnitude of the signal will be incremented. This will wake up on the semaphore blocking process or thread, they go fighting items.

 

reference:

Link: https: //www.jianshu.com/p/eca71b7fda2c

Guess you like

Origin www.cnblogs.com/zkfopen/p/11232153.html