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

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

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

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

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

代码

#include
#include
#include
#include

#include
#include  

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");
}



你可能感兴趣的:(测试sleep()和pthread_cond_timewait()之间的区别)