+ 6

Reusing std::condition_variable object in a thread

I am trying to design a simple program that mimics the functionality of a basic alarm clock. For this, I am using threads. One to keep checking if its time to ring the alarm, one to handle the basic operations like adding a new alarm, and one to handle input during the period when the alarm is active. (using a function named ask_alarm). In ask_alarm, I use a condition_variable object, that waits till it is notified by the try_alarm (alarm checking function) thread. Here is the code for ask_alarm: https://code.sololearn.com/cpIrv6q5T8sW/#cpp void ask_alarm() { unique_lock<mutex> lk(m2); cv.wait(lk,[](){return its_time;}); int res = TimedMessageBox(nullptr,("Alarm \""+Clock.ring()+"\" is active!\n" "Would you like to Switch it off?").c_str(),"Alarm Active!", MB_YESNO|MB_ICONINFORMATION,60000); if(res == IDYES) Program::terminate(); its_time = false; } But the issue is it works the first time there is a match, but then the thread dies and then does not respond to successive alarms. I have tried using a loop, but that does not work as well. How can I keep using this condition variable multiple times, for multiple alarms? If condition_variables won't work in cases like this, then what should I replace them with? I am new to concurrency, and so don't have much idea. I used this as I read that the thread sleeps till the time it is notified by the other thread. Here is the project link, for detailed reference: https://github.com/kinshuk-h/Basic-Alarm-Clock

2nd Jan 2019, 4:52 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
5 Antworten
+ 2
@Rewa Mathur Thank you very much for your help. I highly appreciate it. I am a bit confused. ^_^; As per the code, the integrator runs a separate thread and waits till the other thread returns true, right? If this is not the exact case, please let me know.
4th Jan 2019, 12:59 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Rewa Mathur I think I understand the concept now. Thank you!
4th Jan 2019, 1:10 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar