tags:

views:

346

answers:

1

Hi,

In linux, how can synchronize between 2 thread (using pthreads on linux)? I would like, under some conditions, a thread will block itself and then later on, it will be resume by another thread. In Java, there is wait(), notify() functions. I am looking for something the same on pthreads:

I have read this, but it only has mutex, which is kind of like Java's synchronized keyword. That is not what I am looking for. https://computing.llnl.gov/tutorials/pthreads/#Mutexes

Thank you.

+4  A: 

You need a mutex, a condition variable and a helper variable.

in thread 1:

pthread_mutex_lock(&mtx);

// We wait for helper to change (which is the true indication we are
// ready) and use a condition variable so we can do this efficiently.
while (helper == 0)
{
    pthread_cond_wait(&cv, &mtx);
}

pthread_mutex_unlock(&mtx);

in thread 2:

pthread_mutex_lock(&mtx);

helper = 1;
pthread_cond_signal(&cv);

pthread_mutex_unlock(&mtx);

The reason you need a helper variable is because condition variables can suffer from spurious wakeup. It's the combination of a helper variable and a condition variable that gives you exact semantics and efficient waiting.

R Samuel Klatchko
n179911
@n179911 - notice how pthread_cond_wait() includes the mutex as a parameter; it uses that to unlock/lock the mutex. From the man page of my box "pthread_cond_wait atomically unlocks the mutex (as per pthread_unlock_mutex) and waits for the condition variable cond to be signaled. Before returning to the calling thread, pthread_cond_wait re-acquires the mutex (as per pthread_lock_mutex)"
R Samuel Klatchko