加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在进行sem_timedwait时,我如何应对系统时间的变化?

发布时间:2020-12-15 21:22:59 所属栏目:安全 来源:网络整理
导读:假设我有一个使用sem_timedwait的程序,等待100毫秒(获取当前时间,添加100毫秒,使用结果为abs_timeout,cf. man page).现在,在等待信号量的同时,系统时间由外部进程(ntp)设置. 如果我们运气不好,系统时间设置为过去2天.这将导致sem_timedwait等待2天和100毫秒.
假设我有一个使用sem_timedwait的程序,等待100毫秒(获取当前时间,添加100毫秒,使用结果为abs_timeout,cf. man page).现在,在等待信号量的同时,系统时间由外部进程(ntp)设置.

如果我们运气不好,系统时间设置为过去2天.这将导致sem_timedwait等待2天和100毫秒.

有办法解决这个问题吗?

解决方法

您可以改为使用条件变量,并选择单调时钟作为参考时钟.信号量有点老,我会避免在新的应用程序中使用它们.如果您愿意,可以使用条件变量和互斥量轻松实现信号量.

pthread_condattr_t cattr;
pthread_condattr_init(&cattr);
pthread_condattr_setclock(&cattr,CLOCK_MONOTONIC);

pthread_cond_t cond;
pthread_cond_init(&cond,&cattr);

struct timespec ts;
clock_gettime(CLOCK_MONOTONIC,&ts);
ts.tv_nsec += 100000000;
if (ts.tv_nsec >= 1000000000) {
    ts.tv_nsec -= 1000000000;
    ts.tv_sec += 1;
}
int r = pthread_cond_timedwait(&cond,&mutex,&ts);
if (r == ETIMEDOUT) {
    // ...
} else {
    // ...
}

单调时钟“不受系统时间内不连续跳跃的影响”(man clock_gettime),因此它正是您对此类应用所需要的.

你说,

Now it happens that the system time gets set by an external process (ntp) while waiting for the semaphore.

但情况比这更糟糕……系统时钟可能会在你调用clock_gettime()之后调用sem_timedwait()之前进行调整……所以就你所知,你希望sem_timedwait()等待两天.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读