Why doesn't C++ wait unconditionally in the thread?
This article mainly explains "Why C++ should not wait unconditionally in the thread". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought slowly and deeply. Let's study and learn why C++ does not wait unconditionally in the thread.
CP.42: don't wait unconditionally
Reason (reason)
A wait without a condition can miss a wakeup or wakeup simply to find that there is no work to do.
Unconditional waiting may miss the wake-up call, or wake up and find that there is nothing to do.
Example, bad (negative example)
Std::condition_variable cv;std::mutex mx
Void thread1 () {while (true) {/ / do some work... Std::unique_lock lock (mx); cv.notify_one (); / / wake other thread}}
Void thread2 () {while (true) {std::unique_lock lock (mx); cv.wait (lock); / / might block forever / / do work...}}
Here, if some other thread consumes thread1's notification, thread2 can wait forever.
Here, if some other thread consumes the notification from thread 1, thread 2 will wait forever.
Example (sample)
Templateclass Sync_queue {public: void put (const T & val); void put (val & val); void get (T & val); private: mutex mtx; condition_variable cond; / / this controls access list q;}
Templatevoid Sync_queue::put (const T & val) {lock_guard lck (mtx); q.push_back (val); cond.notify_one ();}
Templatevoid Sync_queue::get (T & val) {unique_lock lck (mtx); cond.wait (lck, [this] {return! q.empty ();}); / / prevent spurious wakeup val = q.front (); q.pop_front ();}
Now if the queue is empty when a thread executing get () wakes up (e.g., because another thread has gotten to get () before it), it will immediately go back to sleep, waiting.
Now, when a thread performs a get wake-up, if the queue is empty (for example, another thread of the user has already executed the get in advance), it will immediately go back to sleep and wait.
Enforcement (implementation recommendations)
Flag all waits without conditions.
Mark all unconditional waiting.
Thank you for your reading, the above is the content of "Why C++ does not wait unconditionally in the thread". After the study of this article, I believe you have a deeper understanding of why C++ should not wait unconditionally in the thread. The specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!