Background
I'm currently developing a program using C++11 for the raspberry pi. The basic design (relevant to this question) is:
- I have a main loop that's awaiting commands from an external source.
- In the main loop I create an agent (object that's running in a separate thread) which sleeps until something is added to its queue, in which case it awakens, processes this item, and then checks if there are any items in the queue again before going back to sleep (this process repeats if there is more to process)
In the "processing" of the item, I am simply enabling/disabling GPIO pins one at a time for X amount of seconds.
Processing pseudo-code:
for (Pin pin : pins)
{
set_pin(pin, HIGH);
this_thread::sleep_for(chrono::seconds(x))
set_pin(pin, LOW);
this_thread::sleep_for(chrono::seconds(y))
}
Obviously, 99.999% of the time of this thread is going to be spent asleep (the only time it's executing code is when it's setting pin outputs (no data is touched here)
Question
How should I go about canceling the processing of the current item from the main thread? I don't want to kill the thread, ever, I just want it to return to it's run loop to process the next item in the queue (or go back to sleep).
I can think of ways to do this, I would just like to hear several ideas from the community and choose the best solution.
Additional code
This is the class running in a separate thread doing the processing of items in the queue.
schedule->RunSchedule(schedule)
is the call to the function described by the pseudo-code above.
ScheduleThread.cpp
#include "ScheduleThread.h"
ScheduleThread::ScheduleThread()
: thread(&ScheduleThread::run, this)
{
}
ScheduleThread::~ScheduleThread() {
// TODO Auto-generated destructor stub
}
void ScheduleThread::QueueSchedule(Schedule *schedule)
{
lock_guard<mutex> lock(m);
schedule_queue.push(schedule);
stateChangedSema.post();
}
bool ScheduleThread::scheduler()
{
if (!schedule_queue.empty())
{
Schedule *schedule = schedule_queue.front();
schedule->RunSchedule();
schedule_queue.pop();
return true;
}
return false;
}
void ScheduleThread::run()
{
for(;;)
{
stateChangedSema.wait();
while (scheduler());
}
}
Thanks in advance for any help.