gpt4 book ai didi

c - 在什么系统上 sleep() 不是 pthread 取消点?

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:21 24 4
gpt4 key购买 nike

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

最佳答案

sleep() 是 POSIX 要求的取消点(有关取消点列表,请参阅 this link。)

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com