monkeyking
monkeyking

Reputation: 6948

using a mutex as a condition variable

Given the canonical example for condition variables

pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&count_threshold_cv, &count_mutex);

Then I can send a signal from another thread, and this thread will continue.

But I fail to see whats wrong with just trying to lock a mutex, and if the lock is taken then the thread will wait for the mutex lock to be released.

Is the only problem with this approach the constant polling?

Thanks

Upvotes: 2

Views: 460

Answers (2)

Nemo
Nemo

Reputation: 71515

Let's make this concrete. Your suggested alternative to condition variables is for the "waiter" to do this:

loop:
    lock mutex
    check predicate
    if (predicate is false)
        unlock mutex
        sleep a bit // (is this what you had in mind?)
        goto loop

And for the "signaler" to do this:

    lock mutex
    make predicate true
    unlock mutex

Here, "predicate" might be "the queue is not empty", for instance.

There are two problems with this approach. The first is the one you identified: The constant polling is inefficient. If you imagine hundreds or thousands of threads across the whole system trying to operate this way, it would bring the system to its knees. Or your "sleep a bit" would have to be so long that the sleeps themselves would add up to annoying delays.

The second problem is more subtle. There is no guarantee that when a thread unlocks a mutex and then locks it again, another thread waiting on that mutex will be allowed to run. (This property of a mutex is called "fairness"; a mutex that provides it is said to be "fair". POSIX does not require mutexes to be fair.) No matter how long you sleep in the "waiter", there is no guarantee that the "signaler" will ever get past its lock mutex call.

Condition variables solve both of these problems.

Upvotes: 7

ninjalj
ninjalj

Reputation: 43688

Condition variables signal changes to data structures protected by mutexes. E.g. you may have a queue protected by a mutex, and when it gets empty, you want the consumer to wait on a condition variable until the queue is no longer empty. You want to atomically release the mutex and wait in that situation.

Upvotes: 0

Related Questions