/**************************************************************************************/
/*文件: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]#