2

pthread_cancel() 在 Solaris 10、Linux 和 Cygwin 上成功中断 sleep()。那么为什么人们使用 pthread_cond_timedwait() 而不是 sleep() 呢?
在以下示例中,PPBsleep() 是我在某个库中找到的函数。我认为它容易受到系统时钟调整的影响。

PPBsleep2() 我自己写的。我认为它并不比 PPBsleep() 差。简单的 sleep() 也可以。

#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;
}
4

1 回答 1

2

sleep()需要成为 POSIX 的取消点(有关取消点列表,请参阅此链接。)

因此,它应该作为任何 POSIX 兼容系统的取消点。

于 2013-06-06T09:16:09.483 回答