C++11 Multithreading
Overview
C++11 Multithreading - Create Threads
C++11 Multithreading - Mutex Lock
C++11 Multithreading - Condition Variable
C++11 Multithreading - Semaphore
C++11 Multithreading - The Bounded-Buffer Problem
Mutex Lock vs Condition Variable vs Semaphore
Mutex stands for mutual exclusion. Mutex locks are used for mutual exclusion only. When you want to ensure that a piece of code is atomic, put a lock around it. You could theoretically use a binary semaphore to do this, but that's a special case.
Condition variables and Semaphores build on top of the mutual exclusion provide by locks and are used for providing synchronized access to shared resources. They can be used for similar purposes.
A condition variable is generally used to avoid busy waiting (looping repeatedly while checking a condition) while waiting for a resource to become available.
Semaphores can be used similarly, but I think they're better used when you have a shared resource that can be available and unavailable based on some integer number of available things. Semaphores are good for producer/consumer situations where producers are allocating resources and consumers are consuming them.
Conditional variable is essentially a wait-queue, that supports blocking-wait and wakeup operations, i.e. you can put a thread into the wait-queue and set its state to BLOCK, and get a thread out from it and set its state to READY.
Note that to use a conditional variable, two other elements are needed:
- a condition (typically implemented by checking a flag or a counter)
- a mutex that protects the condition
The protocol then becomes,
- acquire mutex
- check condition
- block and release mutex if condition is true, else release mutex
Semaphore is essentially a counter + a mutex + a wait queue. And it can be used as it is without external dependencies. You can use it either as a mutex or as a conditional variable.
Therefore, semaphore can be treated as a more sophisticated structure than conditional variable, while the latter is more lightweight and flexible.
Reference
https://stackoverflow.com/questions/3513045/conditional-variable-vs-semaphore

浙公网安备 33010602011771号