当前位置: 技术问答>linux和unix
互斥锁和条件变量同步线程等待超时程序问题
来源: 互联网 发布时间:2017-01-15
本文导语: /**************************************************************************************/ /*文件:pthread_cond.c */ /*简介:互斥锁和条件变量同步线程等待超时程序 ...
/**************************************************************************************/
/*文件: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]#
|
补充一下:
此时互斥锁count_lock不会被占用,此时increment_count才能得到互斥锁,只有increment_count释放了锁之后,decrement_count才能得到锁再继续执行。
while (count == 0)
k = pthread_cond_timedwait(&count_ready, &count_lock, &t);
此时互斥锁count_lock不会被占用,此时increment_count才能得到互斥锁,只有increment_count释放了锁之后,decrement_count才能得到锁再继续执行。
|
1.decrease线程 count_lock加锁 --> 等待count_ready(解锁count_lock)
2.increase线程 count_lock加锁 --> count_ready通知 --> 解锁count_lock
直接等待count_lock,其他线程怎么工作
2.increase线程 count_lock加锁 --> count_ready通知 --> 解锁count_lock
直接等待count_lock,其他线程怎么工作
|
你的程序写的有点问题
|
程序编译不通过
error: too few arguments to function ‘int gettimeofday(timeval*, timezone*)’
error: too few arguments to function ‘int gettimeofday(timeval*, timezone*)’