Anisha Kaul, there are a few details missing in your explanation. The main one is that ThreadB must also lock the mutex.
Perhaps example code would make it clearer for others? (And do say so if you disagree with the following snippets!)
First, the two threads will need a common mutex and a condition variable, in addition to the counter. The condition variable is used to wake up any waiters. The type of the counter variable doesn't matter.
All threads must lock the mutex before accessing the counter.
Code:
int counter;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t counter_wait = PTHREAD_COND_INITIALIZER;
When a thread modifies the counter, it should also signal or broadcast on the condition variable to wake up any waiters. Signaling wakes up a random one, and broadcasting wakes up all. Broadcasting causes a bit of a thundering herd among the waiters, so it is not the most efficient option; but usually it is the one you'll need. (You can only rely on signaling instead of broadcasting, if you
know all waiters wait for the counter to change. If any of them wait for the counter to change
to a specific value, you must use broadcast, to make sure each waiter checks the new counter value.)
Code:
if (pthread_mutex_lock(&counter_lock)) {
/* Fatal error: Deadlock or damaged mutex! */
exit(1);
}
/* Modify counter */
counter++;
/* Wake up all threads waiting for the counter to change.
* Note: pthread_cond_broadcast() never returns an error code. */
pthread_cond_broadcast(&counter_wait);
if (pthread_mutex_unlock(&counter_lock)) {
/* Fatal error: Damaged mutex! */
exit(1);
}
In many applications you can omit the error checking for the functions. However, I recommend always checking the
pthread_mutex_lock() return value for
deadlock.
Let us assume the other thread wishes to wait until the counter reaches a certain value. I personally avoid checking for a
specific value using ==, to avoid race conditions: other threads can easily manage to increase the counter twice before a waiting thread gets the mutex!
Code:
if (pthread_mutex_lock(&counter_lock)) {
/* Fatal error: Deadlock or damaged mutex! */
exit(1);
}
/* Waiting loop: inspect each counter value, and if not desired yet, wait.
* Note: pthread_cond_wait() never returns an error. */
while (counter < some_value)
pthread_cond_wait(&counter_wait, &counter_lock);
/* Okay, counter >= some_value now.
* Note that the mutex is locked, and we can access counter here.
*/
if (pthread_mutex_unlock(&counter_lock)) {
/* Fatal error: Damaged mutex! */
exit(1);
}