What are the pits that use conditional variables?
This article introduces the relevant knowledge of "what are the pits for the use of conditional variables". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. What is a conditional variable?
Conditional variables are commonly used to implement wait and wake-up logic in multithreaded programs. There are usually two actions, wait and notify, and wait is used to block pending thread A until another thread B wakes up thread A through notify, and thread A continues to run after waking up.
Conditional variables are commonly used in multithreading. In the famous producer and consumer problems, how do consumers know whether the producer has produced a consumable product, and constantly judge whether there is a consumable product through the while cycle? As we all know, a dead loop consumes extremely much CPU performance, so you need to use conditional variables to block threads and reduce CPU utilization.
two。 The use of conditional variables
Taking producer and consumer issues as an example, take a look at the following code:
Std::mutex mutex; std::condition_variable cv; std::vector vec; void Consume () {std::unique_lock lock (mutex); cv.wait (lock); std::cout