I'm trying to synchonise a set of threads. These threads sleep most of the time, waking up to do their scheduled job. I'm using std::thread
for them.
Unfortunately, when I terminate the application threads prevent it from exiting. In C# I can make a thread to be background
so that it will be termianted on app exit. It seems to me that equavalint feature is not availabe at C++.
So I decided to use a kind of event indicator, and make the threads to wake up when the app exits. Standard C++11 std::condition_variable
requires a unique lock, so I cannot use it, as I need both threads to wake up at the same time (they do not share any resources).
Eventually, I decided to use WinApi's CreateEvent
+ SetEvent
+WaitForSingleObject
in order to solve the issue.
I there a way to achieve the same behavior using just c++11?
Again, what do I want:
- a set of threads are working independently and usually are asleep for a particular period (could be different for different threads;
all threds check a variable that is availabe for all of them whether it is a time to stop working (I call this variable
IsAliva
). Actually all threads are spinning in loop like this:while (IsAlive) { // Do work std::this_thread::sleep_for(...); }
- threads must be able to work simultaneously, not blocking each other;
- when the app is closed and event is risen and it makes the thread to wake up right now, no matter the timeout;
- waken up, it checks the
IsAlive
and exits.