I have a background thread:
class Queue
{
public:
Message* WaitForMessage(uint32_t uTimeOutMS);
private:
SignalObject soMessage; // Signalled when a message is added to the queue
};
class MyThread : Thread
{
public:
bool IsToStop() const { return soStop.IsSignalled(); }
void ThreadFunction()
{
while (!IsToStop()) {
Message* pMessage = queue1.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
pMessage = queue2.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
Sleep(100); etal // If I wait for 1 ms I hog the CPU, if I wait for 100 ms I waste time when the thread should be stopped
};
}
private:
SignalObject soStop; // Signalled when the thread should stop
Queue queue1;
Queue queue2;
};
I would like to get rid of the Sleep and just wait on the signal objects at the same time (This should free up some CPU while I wait for the signal objects).
I could make them the signal objects on the Queue public and then do something like this:
while (true) {
WaitForSignalObjectsForever(soStop, queue1.soMessage, queue2.soMessage); // Returns after any signal object is signalled
if (IsToStop()) break;
Message* pMessage = queue1.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
pMessage = queue2.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
}
or this:
while (true) {
soStop.WaitForSignalObjectsForever(queue1.soMessage, queue2.soMessage); // Returns after any signal object is signalled
if (IsToStop()) break;
Message* pMessage = queue1.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
pMessage = queue2.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
}
or this:
while (WaitForSignalObjectsOrIsToStopForever(queue2.soMessage, queue1.soMessage)) { // Returns true if soStop is signalled, false if one of the other signal objects was signalled
Message* pMessage = queue1.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
pMessage = queue2.GetMessage();
if (pMessage != nullptr) ProcessMessage(pMessage);
}
I think I prefer the first version because it is more generic. I still feel icky about making the signal objects public (Or protected with friend access) though. Does any one have a better solution?
Also I am used to calling them signal objects, is there a more common name for them?
in windows you have WaitForMultipleObjects, you could write something like this ( in pseudo code )
another solution would be to create several threads for monitoring the queue’s:
and in the master thread do something like this: ( using condition + mutex from boost/thread.hpp )