pthread_cond_timedwait()

前端 未结 7 1538
有刺的猬
有刺的猬 2020-12-16 05:22
void wait(int timeInMs)
{
    struct timespec timeToWait;
    timeToWait.tv_sec = 5;
    timeToWait.tv_nsec = timeInMs*1000;

    int rt;

    pthread_mutex_lock(&am         


        
相关标签:
7条回答
  • 2020-12-16 06:18

    Here is an example where I have created a thread from main loop which does a scan of a directory and have a timeout of 5 sec. And signalling from the thread happens using a conditional variable which is a global. We keep checking for this signal from thread:

        pthread_cond_t C_KISU_SwagntUtilityBase::m_cond; /*Global variable*/
    /*Inside main function*/    
    /*Local variables*/
              pthread_condattr_t l_attr;
              pthread_condattr_init(&l_attr);
              pthread_condattr_setclock(&l_attr, CLOCK_MONOTONIC);
              pthread_cond_init(&C_KISU_SwagntUtilityBase::m_cond, &l_attr);
    
              Int32 l_threadid = pthread_create(&l_updatethread,NULL,C_KISU_SwagntUtilityBase::ThreadScanDirectoryByFilter,&l_filer);
              if(CMP_ZERO == l_threadid)
              {
                pthread_mutex_t l_mutex = PTHREAD_MUTEX_INITIALIZER;
                struct timespec l_ts;
                if (clock_gettime(CLOCK_MONOTONIC, &l_ts) == INIT_NEGONE)
                {
                 /* Handle error */
                }
                printf("\n Setting max time to  run ThreadScanDirectoryByFilter as 5 second"));
                l_ts.tv_sec += l_filer.m_max_scan_time;
    
                if(l_filer.m_scan_status == 0)
                {
                  pthread_mutex_lock(&l_mutex);
                  int l_rt = pthread_cond_timedwait(&C_KISU_SwagntUtilityBase::m_cond, &l_mutex, &l_ts);
                  if (ETIMEDOUT == l_rt)
                  {
                    printf("\n timeout has happened before scan routine could finish"));
                  }
                  else if (EOK  == l_rt)
                  {
                    printf("\n Scan successful"));
                  }
                  else
                  {
                    printf("\n Unknown error while timeout condition check"));
                  }
                  pthread_mutex_unlock(&l_mutex);
                }
              }
              else
              {
                printf("\n Error while creating thread\n");
    
              }
    
    0 讨论(0)
提交回复
热议问题