C++ - How not to miss multiple notifications from multiple threads? - c++

In my application, many threads notify a waiting thread. Sometimes these notifications are very close to each other in time and the waiting thread misses the notification. Is there any easy way to counter this issue? A small example code is given below. In the code, the task2 notifies the waiting thread but the waiting thread, waitingForWork, miss the notification.
#include <condition_variable>
#include <iostream>
#include <thread>
std::mutex mutex_;
std::condition_variable condVar;
bool dataReady{ false };
void waitingForWork() {
for (int i = 0; i < 2; i++)
{
std::cout << "Waiting " << std::endl;
std::unique_lock<std::mutex> lck(mutex_);
condVar.wait(lck, [] { return dataReady; });
dataReady = false;
std::cout << "Running " << std::endl;
}
}
void task1() {
std::this_thread::sleep_for(std::chrono::milliseconds{ 45 });
std::lock_guard<std::mutex> lck(mutex_);
dataReady = true;
std::cout << "Task1 Done:" << std::endl;
condVar.notify_one();
}
void task2() {
std::this_thread::sleep_for(std::chrono::milliseconds{ 46 });
std::lock_guard<std::mutex> lck(mutex_);
dataReady = true;
std::cout << "Task2 Done" << std::endl;
condVar.notify_one();
}
int main() {
std::cout << std::endl;
std::thread t1(waitingForWork);
std::thread t2(task1);
std::thread t3(task2);
t1.join();
t2.join();
t3.join();
std::cout << std::endl;
system("pause");
}

It's a multiple producer single consumer problem. Which is described here:
Multiple consumer single producer problem
So basically you have to change your code in a way that each thread have to write notifications into a threadsafe queue.
And then your worker thread has to work on this queue and will not miss anymore notifications.

Related

An example condition_variable::notify_one

from
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;
void waits()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cout << "Waiting... \n";
cv.wait(lk, []{return i == 1;});
std::cout << "...finished waiting; i == " << i << '\n';
done = true;
}
void signals()
{
std::this_thread::sleep_for(200ms);
std::cout << "Notifying falsely...\n";
cv.notify_one(); // waiting thread is notified with i == 0.
// cv.wait wakes up, checks i, and goes back to waiting
std::this_thread::sleep_for(300ms); // Add to make sure 'waits' thread wakes up**
std::unique_lock<std::mutex> lk(cv_m);
i = 1;
while (!done)
{
std::cout << "Notifying true change...\n";
lk.unlock();
cv.notify_one(); // waiting thread is notified with i == 1, cv.wait returns**
std::this_thread::sleep_for(300ms);
lk.lock();
}
}
int main()
{
std::thread t1(waits), t2(signals);
t1.join();
t2.join();
}
This is an example I got from cppreference. I have tried to execute the codes and observe the second notify seems not effected. Even I commented it out, the "signals" thread is still done.
Should it be put in the forever loop ??
Also if I add a wait before taking the cv_m mutex, seems it's working as expected

c++ multithreading: condition variable

I am new to multithreading. Here is what I want
thread_function(){
// do job1;
//wait main thread to notify;
// do job2;
}
main(){
//create two threads
//wait both threads to finish job1
//finish job3, then let both threads start job2
//wait both threads to join
}
What is the best way to do this? Thanks.
Here is my code
void job1(){
}
void job2(){
}
void job3(){
}
int main(){
thread t11(job1);
thread t12(job1);
t11.join();
t12.join();
job3();
thread t21(job2);
thread t22(job2);
t21.join();
t22.join();
}
My question is whether I can combine job1 and job2 to one function, and use condition variable to control the order?
I will give you a sample (something similar to producer-consumer problem)
This is not the exact solution you are looking for, but below code will guide you,
Below "q" is protected by mutex, on which the condition variable waits for it to get notified or the !q.empty(needed for spurious wakeups) or time-out.
std::condition_variable cond;
std::deque<int> q;
std::mutex mu;
void function_1() {
int count = 50;
while (count > 0)
{
// Condition variables when used lock should be unique_lock
// lock the resource
std::unique_lock<mutex> locker(mu);
// defer the lock until further
//std::unique_lock<mutex> locker(mu, std::defer_lock);
q.push_front(count);
locker.unlock();
//cond.notify_one();
cond.notify_all();
//std::this_thread::sleep_for(chrono::seconds(1));
count--;
}
}
void function_2(int x,int y) {
int data = 0;
while (data != 1)
{
// mu is the common mutex this resource is protected for the q.
std::unique_lock<mutex> locker(mu);
// this will only be done when !q.empty()
// This will make sure it is handled by multiple threads
auto now = std::chrono::system_clock::now();
if (cond.wait_until(locker, now + y * 100ms, []() { return !q.empty(); }))
{
auto nowx = std::chrono::system_clock::now();
cout << "Thread " << x << "waited for " << (nowx-now).count() << endl;
}
else
{
cout << "Timed out " << endl;
break;
}
data = q.back();
q.pop_back();
locker.unlock();
cout << x << " got value from t1 " << data << endl;
}
}
int main()
{
std::thread t1(function_1);
std::thread t2(function_2,1,50);
std::thread t3(function_2,2,60);
std::thread t4(function_2,3,100);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}

C++ Timer pausing execution of program until finished

C++, XCode 4.6.3, OSX 10.8.2, deploying on iOS
I am trying to create a timed event.
My thought process was to create a thread, do the timing in it and then at the end have it call another function. This is working however it is pausing the rest of the program.
//Launch a thread
std::thread t1(start_thread);
//Join the thread with the main thread
t1.join();
void start_thread()
{
std::cout << "thread started" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
stop_thread();
}
void stop_thread()
{
std::cout << "thread stopped." << std::endl;
}
Is there a way to do this that doesn't pause program execution?
Update:
I could declare the thread in the header file and join in the stop_thread():
void stop_thread()
{
std::cout << "thread stopped." << std::endl;
ti.join();
}
but that throws:
Type 'std::thread' does not provide a call operator
UPDATE 2: Calling t1.detach() instead of join seems to work.
You're right it works:
Here is an example coming from cpp reference
http://en.cppreference.com/w/cpp/thread/thread/detach
#include <iostream>
#include <chrono>
#include <thread>
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Exiting concurrent thread.\n";
}
void threadCaller()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Exiting thread caller.\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
Output:
Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.
We see that the concurrent thread ends after the thread caller ends. This is not possible if detach is not called.
Hope that helps, but Jason found the solution.
Use a class instead.
enum{ PAUSED, STARTED, STOPPED };
class AsyncEvent
{
protected:
unsigned char mState;
public:
AsyncEvent():mState(PAUSED){ mThread = std::thread(&AsyncEvent::run,this); }
~AsyncEvent(){ mThread.join(); }
private:
std::thread mThread;
void run()
{
std::cout << "thread started" << std::endl;
while(mState != STOPPED)
{
if(mState == PAUSED)break;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
}
}
void stop()
{
mState = STOPPED;
}
void pause()
{
mState = PAUSED;
}
};

Understanding the example of using std::condition_variable

There is example of using condition_variable taken from cppreference.com:
#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
int main()
{
std::queue<int> produced_nums;
std::mutex m;
std::condition_variable cond_var;
bool done = false;
bool notified = false;
std::thread producer([&]() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::lock_guard<std::mutex> lock(m);
std::cout << "producing " << i << '\n';
produced_nums.push(i);
notified = true;
cond_var.notify_one();
}
std::lock_guard<std::mutex> lock(m);
notified = true;
done = true;
cond_var.notify_one();
});
std::thread consumer([&]() {
while (!done) {
std::unique_lock<std::mutex> lock(m);
while (!notified) { // loop to avoid spurious wakeups
cond_var.wait(lock);
}
while (!produced_nums.empty()) {
std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
}
});
producer.join();
consumer.join();
}
If variable done comes true before the consumer thread is started, the consumer thread will not get any message. Indeed, sleep_for(seconds(1)) almost avoids such situation, but could it be possible in theory (or if don't have sleep in code)?
In my opinion correct version should look like this to force running consumer loop at least once:
std::thread consumer([&]() {
std::unique_lock<std::mutex> lock(m);
do {
while (!notified || !done) { // loop to avoid spurious wakeups
cond_var.wait(lock);
}
while (!produced_nums.empty()) {
std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
} while (!done);
});
Yes, you are absolutely right: there is a (remote) possibility that the consumer thread will not start running until after done has been set. Further, the write to done in the producer thread and the read in the consumer thread produce a race condition, and the behavior is undefined. Same problem in your version. Wrap the mutex around the entire loop in each function. Sorry, don't have the energy to write the correct code.

Boost Thread Synchronization

I don't see synchronized output when i comment the the line wait(1) in thread(). can I make them run at the same time (one after another) without having to use 'wait(1)'?
#include <boost/thread.hpp>
#include <iostream>
void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
boost::mutex mutex;
void thread()
{
for (int i = 0; i < 100; ++i)
{
wait(1);
mutex.lock();
std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
mutex.unlock();
}
}
int main()
{
boost::thread t1(thread);
boost::thread t2(thread);
t1.join();
t2.join();
}
"at the same time (one after another)" is contradictory. With a call to sleep() they run at the same time. Without a call to sleep(), they run one after another. With only 100 lines to output, thread t1 completes before t2 has a change to begin execution. On my computer, I had to set your loop counter to 10000 before t1 ran long enough for t2 to launch while t1 was still executing:
Thread 0x2305010: 0
Thread 0x2305010: 1
Thread 0x2305010: 2
...
Thread 0x2305010: 8730
Thread 0x2305010: 8731
Thread 0x23052a0: 0
Thread 0x23052a0: 1
...
Thread 0x23052a0: 146
Thread 0x23052a0: 147
Thread 0x2305010: 8732
Thread 0x2305010: 8733
etc
Oh, and yes, if your goal was to make the two threads take turns executing, boost::condition_variable is the solution:
boost::mutex mutex;
boost::condition_variable cv;
void thread()
{
for (int i = 0; i < 100; ++i)
{
boost::unique_lock<boost::mutex> lock(mutex);
std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
cv.notify_one();
cv.wait(lock);
}
cv.notify_one();
}