linux条件变量唤醒丢失,为什么用条件变量同步时,发生信号丢失呢?

一个线程自加计数变量,如果被3整除,唤醒另一个等待线程输入该变量。代码如下:

#include

#include

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int signaled = 0, count = 0;

void* fun1(void* args) {

for (;;) {

pthread_mutex_lock(&lock);

count++;

if (count % 3 == 0) {

pthread_cond_signal(&cond);

if (count > 1000) {

signaled = 1;

pthread_mutex_unlock(&lock);

break;

}

}

pthread_mutex_unlock(&lock);

}

}

void* fun2(void* args) {

pthread_mutex_lock(&lock);

while (!signaled) {

pthread_cond_wait(&cond, &lock);

printf("%d\n", count);

}

pthread_mutex_unlock(&lock);

}

int main() {

pthread_t pthid_1, pthid_2;

pthread_create(&pthid_1, NULL, fun1, NULL);

pthread_create(&pthid_2, NULL, fun2, NULL);

void* result;

pthread_join(pthid_1, &result);

pthread_join(pthid_2, &result);

pthread_cond_destroy(&cond);

pthread_mutex_destroy(&lock);

return 0;

}

正确结果应该是:3 6 9..... 这样的。

现在的输出是:734 747 762....

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值