开发者

Synchronization among 2 threads in linux pthreads

开发者 https://www.devze.com 2022-12-18 06:08 出处:网络
In linux, how can synchronize between 2 thread (using pthreads on linux开发者_StackOverflow中文版)?

In linux, how can synchronize between 2 thread (using pthreads on linux开发者_StackOverflow中文版)? 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.


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.


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

depending on your application specific, they might be more appropriate than mutex

0

精彩评论

暂无评论...
验证码 换一张
取 消