2019年1月30日 星期三

pthread_cond_timedwait pthread_cond_signal 用法

改變另一個thread的睡眠時間


#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

pthread_cond_t c;

void *test(void *param){
 int retval;
 int *sleepTime = (int *)param;
 pthread_condattr_t attr;
 struct timespec to;
 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
 
 pthread_condattr_init( &attr);
 pthread_condattr_setclock( &attr, CLOCK_MONOTONIC);
 pthread_cond_init( &c, &attr); 
 
 while(1){  
  if ((retval = pthread_mutex_lock(&m))) {
   printf("pthread_mutex_lock lock fail fun=%s line=%d\n",__FUNCTION__,__LINE__);
   break;  
  }
  
  clock_gettime(CLOCK_MONOTONIC, &to);
  to.tv_sec += *sleepTime;
  
  printf("sleep time is %d sec fun=%s line=%d\n",*sleepTime, __FUNCTION__, __LINE__);
 
  pthread_cond_timedwait(&c, &m, &to);

  if ((retval = pthread_mutex_unlock(&m))) {
   printf("pthread_mutex_unlock unlock fail fun=%s line=%d\n",__FUNCTION__,__LINE__);
   break;
  }
 }
 
 pthread_exit(0);
}

int main(){
 pthread_t tid;
 pthread_attr_t attr;
 int sleepTime = 5;
 
 pthread_attr_init(&attr);
 pthread_create(&tid, &attr, test, &sleepTime);
 
 printf("@@@ please input sleep time\n");
 while(1){
  scanf("%d",&sleepTime);
  printf("sleep time change to %d sec\n",sleepTime);
  pthread_cond_signal(&c);
 }

 return 0;
}
編譯指令: g++ test3.cpp -lpthread -lrt -o test

沒有留言:

張貼留言