测试sleep()和pthread_cond_timewait()之间的区别

这篇博客探讨了sleep()和pthread_cond_timewait()在多线程编程中的不同,通过实验来展示两者在等待条件满足时的响应机制。当条件满足时,会使用pthread_cond_signal()进行唤醒操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用来测试sleep()和pthread_cond_timewait()之间的区别

通过#if 0/1 来分别测试

当从终端输入q时,通过打印来判断是否可以立即返回结束线程,还是要等睡眠时间到了才能结束线程。

当条件满足时,pthread_cond_signal()来触发

代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

#include<pthread.h>
#include <signal.h> 

int flag = 1;
void* print_a(void*);
void* print_b(void*);

pthread_cond_t		cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t		cond_mutex = PTHREAD_MUTEX_INITIALIZER;

int main()
{
	pthread_t pth[2];
	char c;

	if(pthread_create(&pth[0],NULL,print_a,NULL) ==-1)
	{
		printf("----pth[0]error--------\n");
		exit(-1);
	}


	if(pthread_create(&pth[1],NULL,print_b,NULL) ==-1)
	{
		printf("----pth[1]error--------\n");
		exit(-1);
	}


	while ((c = getchar()) != 'q');
	
	flag = 0;
	
	
	printf("----end----------\n");
	
	pthread_cond_signal(&cond);  
	
        if(pthread_join(pth[0], NULL) == -1){
            puts("fail to recollect t0");
            exit(1);
        }
    
	pthread_cond_signal(&cond);  
	
        if(pthread_join(pth[1], NULL) == -1){
        puts("fail to recollect t1");
        exit(1);
        }

    
	printf("-bye\n");

	return 0 ;
}

void* print_a(void* a)
{
	
	struct	timespec	timeout;
	
	while(flag){

#if 0
		timeout.tv_sec = time(NULL) + 30;
		timeout.tv_nsec = 0;

		//printf("aa\n");
		/* Mutex must be locked for pthread_cond_timedwait... */
		
		pthread_mutex_lock(&cond_mutex);
		/* Thread safe "sleep" */
		pthread_cond_timedwait(&cond, &cond_mutex, &timeout);

		/* No longer needs to be locked */
		pthread_mutex_unlock(&cond_mutex);
#else
		sleep(30);
#endif
	}
	

	printf("----aa-----------\n");
	
}



void* print_b(void* b)
{
	struct	timespec	timeout;
	
	while(flag){
#if 0
		timeout.tv_sec = time(NULL) + 40;
		timeout.tv_nsec = 0;
		pthread_mutex_lock(&cond_mutex);
		printf("bb\n");
		/* Mutex must be locked for pthread_cond_timedwait... */
		
		/* Thread safe "sleep" */
		pthread_cond_timedwait(&cond, &cond_mutex, &timeout);

		/* No longer needs to be locked */
		pthread_mutex_unlock(&cond_mutex);
#else
		sleep(50);
#endif
	}
	
	printf("----bb-----------\n");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值