How to wake up a std::thread while it is sleeping?
Last Updated :
31 Mar, 2021
In this article, we will discuss how to wake up a std::thread while it is sleeping. It is known that a thread can’t be exited when it is sleeping. So it is woken up using a command as:
std::condition_variable
Below is the pseudo-code to implement the same:
C++
struct MyClass {
MyClass()
: my_thread([ this ]() {
this -> thread ();
})
{
}
~MyClass()
{
{
std::lock_guard<std::mutex> l(m_);
stop_ = true ;
}
c_.notify_one();
my_thread.join();
}
void thread ()
{
while ( this ->wait_for(std::chrono::minutes(2)))
SendStatusInfo(some_info);
}
template < class Duration>
bool wait_for(Duration duration)
{
std::unique_lock<std::mutex> l(m_);
return !c_.wait_for(l, duration, [ this ]() {
return stop_;
});
}
std::condition_variable c_;
std::mutex m_;
bool stop_ = false ;
std:: thread my_thread;
};
|
Below is another example to illustrate the same:
std::promise/std::future
The above command can be used as a simpler alternative to the former method. In this case, a Future is not susceptible to false wakes and doesn’t require a mutex for synchronization. Below is the pseudo-code to implement the same:
C++
std::promise< void > pr;
std:: thread thr{
[fut = pr.get_future()]{
while ( true ){
if (fut.wait_for(std::chrono::minutes(2))
!= std::future_status::timeout) return ;
}
}
}
;
pr.set_value();
thr.join();
|
Below is the program to illustrate the above concepts:
C++
#include <bits/stdc++.h>
using namespace std;
std::deque< int > q;
std::mutex mu;
std::condition_variable cond;
void function_1()
{
int count = 10;
while (count > 0) {
std::unique_lock<mutex> locker(mu);
q.push_front(count);
locker.unlock();
cond.notify_one();
std::this_thread::sleep_for(
chrono::seconds(1));
count--;
}
}
void function_2()
{
int data = 0;
while (data != 1) {
std::unique_lock<mutex> locker(mu);
cond.wait(locker, []() {
return !q.empty();
});
data = q.back();
q.pop_back();
locker.unlock();
cout << "t2 got a value from"
" t1"
<< data << '\n' ;
}
}
int main()
{
std:: thread t1(function_1);
std:: thread t2(function_2);
t1.join();
t2.join();
return 0;
}
|
Output:
Share your thoughts in the comments
Please Login to comment...