テストsleep()とpthread_cond_timewait()の違い
2401 ワード
sleep()とpthread_をテストするために使用cond_timewait()の違い
#if 0/1でそれぞれテスト
端末からqが入力されると、印刷によって直ちに終了スレッドに戻ることができるかどうか、またはスリープ時間が来てからスレッドを終了するか否かが判断される.
条件が満たされるとpthread_cond_Signal()でトリガ
コード#コード#
#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--------
");
exit(-1);
}
if(pthread_create(&pth[1],NULL,print_b,NULL) ==-1)
{
printf("----pth[1]error--------
");
exit(-1);
}
while ((c = getchar()) != 'q');
flag = 0;
printf("----end----------
");
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
");
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
");
/* 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-----------
");
}
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
");
/* 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-----------
");
}