Synchronization between two threads in linux pthreads

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

I read this, but it only has a mutex, which seems to be like a synchronized Java keyword. This is not what I am looking for. https://computing.llnl.gov/tutorials/pthreads/#Mutexes

Thanks.

+4
source share
2 answers

You need a mutex, a condition variable, and an auxiliary variable.

in stream 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 stream 2:

 pthread_mutex_lock(&mtx); helper = 1; pthread_cond_signal(&cv); pthread_mutex_unlock(&mtx); 

The reason you need an auxiliary variable is because condition variables can suffer from false awakening . It is a combination of an auxiliary variable and a condition variable that gives you exact semantics and effective expectation.

+11
source

You can also see spin locks. try man / google pthread_spin_init, pthread_spin_lock as a starting point

depending on your application, they may be more suitable than a mutex

0
source

Source: https://habr.com/ru/post/1299374/


All Articles