大家好,又见面了,我是你们的朋友全栈君。
用来测试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");
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/143758.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...