linux 线程锁超时,互斥锁和条件变量同步线程等待超时程序问题

/**************************************************************************************/

/*文件:pthread_cond.c                                         */

/*简介:互斥锁和条件变量同步线程等待超时程序                         */

/*************************************************************************************/

#include

#include

#include

#include

#include

pthread_mutex_t count_lock;

pthread_cond_t count_ready;

int count;

void *decrement_count(void *arg)

{

int k = 3;

struct timeval t1;

gettimeofday(&t1);

struct timespec t;

t.tv_sec = 1 + t1.tv_sec;//设置等待的时间是1s

t.tv_nsec = t1.tv_usec * 1000;

pthread_mutex_lock(&count_lock);

printf("decrement:waitingn");

/*等待满足条件,期间互斥量仍然可用*/

while (count == 0)

k = pthread_cond_timedwait(&count_ready, &count_lock, &t);

//应该是等待超时自动运行下面的?怎么非要等到信号阿?

printf("k = %d cout = %dn%sn", k, count , strerror(k));

count = count - 1;

printf("decrement:count = %dn",  count);

pthread_mutex_unlock(&count_lock);

pthread_exit(NULL);

}

void *increment_count(void *arg)

{

int k;

pthread_mutex_lock(&count_lock);

printf("increment:runningn");

if ((k =sleep(10) )!= 0);

{

printf("%dn", k);

//pthread_exit(NULL);

}//这里程序怎么没停下来,还是往下面走啊?

count = count + 1;

/*通知线程条件已满足*/

pthread_cond_signal(&count_ready);

printf("increment:count = %dn",  count);

pthread_mutex_unlock(&count_lock);

pthread_exit(NULL);

}

int main()

{

pthread_t tid1,tid2;

count=0;

pthread_mutex_init(&count_lock, NULL);

pthread_cond_init(&count_ready, NULL);

pthread_create(&tid1, NULL, decrement_count, NULL);

sleep(1);

pthread_create(&tid2, NULL, increment_count, NULL);

//   /*等待decrement退出*/

pthread_join(tid2, NULL);

printf("decrement quitn");

pthread_join(tid1, NULL);

return 0;

}

等待超时,怎么还是原样运行啊?

这里程序怎么没停下来,还是往下面走啊?

结果:

[root@localhost work1]# ./1

decrement:waiting

increment:running

0

increment:count = 1

decrement quit

k = 110 cout = 1

Connection timed out

decrement:count = 0

[root@localhost work1]#

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值