The previous version had some bugs: the blocking flag was not reset and
it might have tried to execute a canceled (and thus deleted) slot.
#include <algorithm>
+#include <msp/core/raii.h>
#include "timer.h"
#include "utils.h"
MutexLock l(mutex);
while(1)
{
- if(slots.empty())
+ TimeStamp stamp;
+ TimeStamp t = now();
+ if(!slots.empty())
{
- if(block)
- {
- blocking = true;
- mutex.unlock();
- sem.wait();
- mutex.lock();
- }
- else
- return;
+ next = slots.begin()->slot;
+ stamp = next->get_timeout();
+ if(stamp<=t)
+ break;
}
- next = slots.begin()->slot;
- const TimeStamp &stamp = next->get_timeout();
- const TimeStamp t = now();
- if(stamp<=t)
- break;
- else if(block)
+ if(block)
{
- blocking = true;
+ SetFlag setf(blocking);
mutex.unlock();
- sem.wait(stamp-t);
+ if(stamp)
+ sem.wait(stamp-t);
+ else
+ sem.wait();
mutex.lock();
+ // The slots may have changed while waiting so check again
+ continue;
}
else
return;