pthread_cancel()成功中断Solaris 10、Linux和Cygwin上的sleep()。
那么为什么人们使用pthread cond_timedwait()而不是sleep()?
在下面的示例中,PPBsleep()是我在某个库中找到的函数我认为它容易受到系统时钟调整的影响。
PPBsleep2()我自己写的我觉得不比PPBsleep()差普通的睡眠也能起作用。

#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <pthread.h>
#include <errno.h>
#include <stdio.h>

int PPBsleep(int seconds)
{
  int  rc;
  struct timeval now;
  struct timespec timeout;
  pthread_cond_t sleep_cond = PTHREAD_COND_INITIALIZER;
  pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER;

  rc = pthread_mutex_lock(&sleep_mutex);

  rc = gettimeofday(&now,NULL);

  timeout.tv_sec = now.tv_sec + (long)seconds;
  timeout.tv_nsec = now.tv_usec * 1000L;
  rc = 0;
  while(rc != ETIMEDOUT) {
    rc = pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &timeout);
  }

  rc = pthread_mutex_unlock(&sleep_mutex);

  return 0;
}

int PPBsleep2(int seconds)
{
  int oldtype;
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
  sleep(seconds);
  pthread_setcanceltype(oldtype, NULL);
  return 0;
}

void *ThreadStartFunction(void *inp)
{
  pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
  //pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  printf("before sleep\n");
  fflush(stdout);
  //PPBsleep2(4);
  sleep(4);
  printf("after sleep\n");
  fflush(stdout);
  return NULL;
}

int main() {
  int rc;
  void *res;
  pthread_t thread;
  rc = pthread_create(&thread, NULL, ThreadStartFunction, NULL);
  sleep(1);
  pthread_cancel(thread);
  pthread_join(thread, &res);
  return 0;
}

最佳答案

sleep()是POSIX要求的be a取消点(有关取消点的列表,请参见this link。)
因此,它应该作为任何POSIX兼容系统上的取消点。

关于c - 在什么系统上,sleep()不是pthread取消点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16957539/

10-12 01:28