C++ – What’s better for Message Queuing? mutex & cond or mutex & semaphore?

What’s better for Message Queuing? mutex & cond or mutex & semaphore?… here is a solution to the problem.

What’s better for Message Queuing? mutex & cond or mutex & semaphore?

I’m implementing a C++ message queue based on std::queue.

Because I need popers to wait on an empty queue, I consider using mutex for mutual exclusion and cond to suspend threads on an empty queue, just like glib did with gasyncqueue.

But it seems

to me that mutexes and semaphores can do the job, I think it contains an integer, and it seems like a pretty high number for dealing with pending messages.

The advantage of semaphores is that you don’t need to manually check the condition every time you return from waiting, because you can now be sure that someone inserted something (when someone inserted 2 items and you are the second thread to arrive).

Which one will you choose?

Edit:
Changed question in response to @Greg Rogers

Solution

A single semaphore will not do the job – you need to compare (mutex + semaphore) and (mutex + condition variable).

It’s easy to see this by trying to implement it :

void push(T t)
{
    queue.push(t); 
    sem.post();
}

T pop()
{
    sem.wait();
    T t = queue.top();
    queue.pop();
    return t;
}

As you can see, there is no mutex when you actually read/write to the queue, even though the semaphore (from the semaphore) is present. Multiple threads can call push to interrupt the queue at the same time, or multiple threads can call pop to interrupt the queue at the same time. Alternatively, one thread can call pop and remove the first element of the queue, while another thread calls push.

You should use whichever one you think is easier to implement, and I doubt there will be a big difference in performance (although measurements can be interesting).

Related Problems and Solutions