技术解析
根据 stackoverflow 上这篇贴,condition 的用法可以总结为
// safely examine the condition, prevent other threads from
// altering it
pthread_mutex_lock (&lock);
while ( SOME-CONDITION is false)
pthread_cond_wait (&cond, &lock);
// Do whatever you need to do when condition becomes true
do_stuff();
pthread_mutex_unlock (&lock);
请问为什么不直接写成这样呢?
while (true) {
pthread_mutex_lock (&lock);
if ( SOME-CONDITION is true) {
do_stuff();
pthread_mutex_unlock (&lock);
break;
} else {
pthread_mutex_unlock (&lock);
}
}
这样,不需要 condition 这个概念,也可以把临界区保护起来