Q:

Recommended pattern for a queue accessed by multiple threads...what should the worker thread do?

I have a queue of objects that is being added to by a thread A. Thread B is removing objects from the queue and processing them. There may be many threads A and many threads B.
I am using a mutex when the queue in being "push"ed to, and also when "front"ed and "pop"ped from as shown in the pseudo-code as below:
Thread A calls this to add to the queue:
void Add(object)
{
    mutex->lock();
    queue.push(object);
    mutex->unlock();
}

Thread B processes the queue as follows:
object GetNextTargetToWorkOn()
{
    object = NULL;

    mutex->lock();
    if (! queue.empty())
    {
        object = queue.front();
        queue.pop();
    }
    mutex->unlock();

    return(object);
}

void DoTheWork(int param)
{
    while(true)
    {
        object structure;

        while( (object = GetNextTargetToWorkOn()) == NULL)
            boost::thread::sleep(100ms); // sleep a very short time

        // do something with the object
    }    
}

What bothers me is the while---get object---sleep-if-no-object paradigm. While there are objects to process it is fine. But while the thread is waiting for work there are two problems
a) The while loop is whirling consuming resources
b) the sleep means wasted time is a new object comes in to be processed  
Is there a better pattern to achieve the same thing?

A:

You're using spin-waiting, a better design is to use a monitor. Read more on the details on wikipedia.
And a cross-platform solution using std::condition_variable with a good example can be found here.

