【问题标题】:pthread_cond_timedwait not returning after specified timeoutpthread_cond_timedwait 在指定超时后未返回
【发布时间】:2016-03-10 06:38:34
【问题描述】:

在下面的代码中execute_on_thread()会继续打印“.”, 而main 函数等待使用pthread_cond_timedwaitexecute_on_thread 发出条件信号。但是,在指定的 20 秒超时后它并没有超时,它只是继续打印“.”,没有其他任何事情发生。

#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define SHOW_TECH_CMD_MAX_EXEC_TIME       5 //in secs 
pthread_mutex_t waitMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitCond = PTHREAD_COND_INITIALIZER;

void *execute_on_thread();
void *execute_on_thread()
{
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  pthread_mutex_lock( &waitMutex );
  while(1)
  {
    printf(".");
  }
  pthread_cond_signal( &waitCond );
  pthread_mutex_unlock( &waitMutex );
  return (void *) 0;

}
int main( )
{
  pthread_t tid;
  struct timespec   ts;
  int error;
  clock_gettime(CLOCK_REALTIME, &ts);
  ts.tv_sec += 20; 
  pthread_create(&tid,NULL,execute_on_thread,NULL);
  pthread_mutex_lock(&waitMutex);
  error = pthread_cond_timedwait(&waitCond, &waitMutex,&ts);
  pthread_mutex_unlock(&waitMutex);
  printf("come here 1\n");
  if(error == ETIMEDOUT)
  {
    printf("come here 2\n");
    error = pthread_cancel(tid);
    if(error != 0)
    {
       printf("come here 3\n");
    }
  }
}

【问题讨论】:

    标签: pthreads


    【解决方案1】:

    查看pthread_cond_wait 的文档:

    成功返回后,互斥体应已被锁定并应 由调用线程拥有。

    因此,在pthread_cond_wait 返回之前,无论是由于信号到达还是超时,它都会尝试锁定互斥体。但是 - 由于 execute_on_thread 永远不会释放互斥锁(由于 while(1) 循环),pthread_cond_wait 将卡在等待互斥锁解锁。

    例如,如果您将 execute_on_thread 更改为在每个周期中临时解锁互斥锁,您应该能够使其工作。例如:

    void *execute_on_thread()
    {
      pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);   //Not necessary - this is the default state for new threads
      pthread_mutex_lock( &waitMutex );
      while(1)
      {
        printf(".\n");
        pthread_mutex_unlock(&waitMutex);
        usleep(100*1000);                 //So that the screen doesn't completely fill up with '.'s
        pthread_mutex_lock( &waitMutex );
      }
      pthread_cond_signal( &waitCond );
      pthread_mutex_unlock( &waitMutex );
      return (void *) 0;
    }
    

    但请注意,您的程序中还有一些其他方面可以改进 - 例如在条件等待中添加一个保护变量(查看condition variable - why calling pthread_cond_signal() before calling pthread_cond_wait() is a logical error?),添加一个清理处理程序以确保如果在互斥锁锁定和类似调整时由execute_on_thread 处理取消请求,则互斥锁将解锁。

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 2016-04-21
      相关资源
      最近更新 更多