I was wondering if anyone may know of a way to control a timed loop without using concurrency. As it stands I am using threads to carry out operations within a loop and when the timer runs out the loop will stop , however it is causing problems with containers in the way of deletion.
timer(unsignedint period_secs, atomic<bool>& keep_running)
{
constauto interval = chrono::seconds(period_secs);
int cnt = 5;
while (keep_running)
{
{
/*lock_guard<mutex> guard(cout_lock);*/ //<---?
--cnt;
if (cnt == 0) {
keep_running = false;
cout << "end of while loop";
}
}
this_thread::sleep_for(interval);
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
atomic<bool> keep_running{ true };
thread(round_timer, this, 1, ref(keep_running)).detach();
while (keep_running != false) {
dofunc1();
dofunc2();
dofunc3();
}
this_thread::sleep_for(std::chrono::milliseconds(500));
->> otherfuncs(); /problems occur here with other operations
Is there a way possibly to use the lock guard mutex in this instance to prevent these problems? Or any other way to run the loop without disrupting user input within the functions inside the loop without using threads.
JLBorges: if any of the dofunc()'s depend on stdio then they'd block the program even after 5 secs are up, is there a way to get around that? Thanks.
ps. the example I was thinking of is something like this:
> if any of the dofunc()'s depend on stdio then they'd block the program even after 5 secs are up,
> is there a way to get around that?
There is no standard way to do this (fully cancel an i/o operation after a timeout period has expired).
The sentry is constructed and checked before the actual input operation on the stream is attempted. Once the sentry reports that the preparation of the stream object for input was successful, the input request is forwarded to the stream buffer.
So, something like this (which attempts to kill pending input on the stream buffer by setting the stream to a failed state) won't work. (It would abort further attempted input; but it will do so only after the on-going blocking call on the stream buffer has returned.)