【发布时间】:2021-10-16 09:43:03
【问题描述】:
基本问题,但为了简洁起见,我有两个线程bar 在特定条件下解除阻塞foo,但即使程序运行良好令我惊讶,如果foo 不应该导致死锁首先运行它获取锁,这意味着bar 不应该能够继续进行,因为条件变量在foo 中永远不会为真?
pthread_mutex_t lock;
pthread_cond_t cv;
bool dataReady = false;
void foo(void *arg)
{
printf ("Foo...\n");
pthread_mutex_lock(&lock);
while (!dataReady)
{
pthread_cond_wait(&cv, &lock);
}
printf ("Foo unlocked...\n");
dataReady = true;
pthread_mutex_unlock(&lock);
}
void bar(void *arg)
{
printf ("Bar...\n");
pthread_mutex_lock(&lock);
sleep(3);
printf ("Data ready...\n");
dataReady = true;
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&lock);
}
int main(void)
{
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,foo,NULL);
pthread_create(&t2,NULL,bar,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
同样在这种情况下,使用信号量没有意义是吗?
【问题讨论】:
-
"if foo is first run" 我不相信您的代码可以保证
foo将首先获得锁。 -
有一个“如果”。我从来没有谈论过保证,操作系统也不保证。我说它可能首先发生
标签: c multithreading posix