condition var & mutex confusing


I'm new to multi threading.

When I go through the pthread_mutex_t & pthread_cond_t, its bit confusing.

1. For Mutex its stright forward,

Thread1 -> aquire the lock, do the operation and release the lock.
Thread2 => try to aquire the lock, if not avail then wait. once lock is release aquire & release.

2. For Condition variable,

Thread 1 -> aquire the mutex lock, do the operation, release the lock and signal the condition.
Thread 2 -> aquire the same mutex lock, in while loop wait for the conditon, once signaled do operation and release the mutex lock.

a) Already T1 is aquired the mutex lock, but T2 also able to aquire the same mutex lock. How it is possible where in Case 1 its not possible.

b) in while loop i'm putting a contion such as while(NULL == msg) doing cond lock with the same mutex. this looks like normal condition. instead i can a sleep over the loop for that condition.

Can anyone explain bit clearly like what exactly happening in condition varable in threads.


They're different things.

A mutex provides a lock, and is used around shared data. It's the special case of a semaphore where the count is 1.

A condition variable allows something to be signalled. The catch is that is needs to be protected by a mutex, that's why it appears to be so complicated.
@kbw: The purpose of the mutex is not to protect the condition variable. From a man page:
The pthread_cond_wait() function atomically unlocks the mutex argument and waits on the cond argument. Before returning control to the calling function, pthread_cond_wait() re-acquires the mutex.

This allows temporarily unlocking resources while waiting on any condition. You may find this useful in many cases where it would be unacceptable to lock a resources while waiting on some signal.

The main focus of a condition variable concentrates on atomically enclose unlocking of the mutex and start waiting for the condition. Otherwise you may find more than one thread executing the critical section protected by the mutex simultaneously after reacquiring the mutex when receiving a condition signal.
Topic archived. No new replies allowed.