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