Search code examples
c++multithreadingconcurrencytbb

Concurrency efficiency in C++


I have a function pushMessage().

void pushMessage(const char* msg, const int len)
{
    for (int i=0;i<len;++i)
        queue.push(*(msg+i))
}

The queue in question is a tbb::concurrent_bounded_queue<char> and has a really large size (assume infinite).

This function is called by two threads. One thread calls the function constantly, another once in a while.

What's the most efficient way to ensure that the contents of the queue do not have a mix of concurrent msg? My first call was to use mutex, however I'd like to hear more because I am rather new to the world of concurrency, and I'd rather not just jump to the first thing I learn. Much appreciated.

P.S. - I have access to Boost and TBB libraries.

EDIT: The queue is of type char because it is used to send messages byte-by-byte, for speed. The previous implementation was sending the entire messages at a time.


Solution

  • You do not have any other choice but a mutex (or semaphore, or critical section - effectively all the same thing). Nothing else will ensure non-interleaved message in current design.

    I do, however, question the wisdom of the current design. Why are you having a queue of characters, when the semantic is the whole message? Wouldn't it be better to have a whole message as a single queue element?