Shaggi
Shaggi

Reputation: 1161

Choice of semaphores, mutexes and condition variables

I have a producer thread and a consumer thread, with the producer being real-time and determinism-sensitive.

Hence I decided to hoist the processing out of the producer thread into a consumer thread, using a lock-free fifo queue. The goal is to have the consumer being both responsive but also avoiding busy-waiting, while never delaying the producer for a indeterminate amount of time; thus any allocations/locks (and kernel entries, I suppose?) etc. are completely out of the question.

I've implemented this pattern, which seems to work well, however I'm unsure of why a mutex is needed at all:

std::mutex m;
std::condition_variable cv;

void consumer()
{
    std::unique_lock<std::mutex> lock(m);
    while (1)
    {
        cv.wait(lock);
        // process consumation...
    }
}

void producer()
{
    while (1)
    {
        // produce and post..
        cv.notify_one();
    }
}

The other canonical examples seems to lock the mutex in the producer as well, why? My data communication is already thread-safe, so this shouldn't be needed. Also, is this susceptible to missing signals?

And while researching this, I stumble upon semaphores which seem to be used explicitly for this situation. What are the benefits versus this system? I prefer my solution currently, just because it is a part of the standard library.

Upvotes: 2

Views: 1478

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Semaphores and Condition Variables are somehow similar concepts. At least classical Counting Semaphores aren't available natively from the current c++ standard library. But these can be easily replaced with a std::condition_variable controlling an in-/decremented integer value.

The std::mutex for the condition variable is necessary, to protect from race conditions when changing the underlying value.

Upvotes: 2

Related Questions