计时器在C pthread的线程? [英] timer in a thread with pthread in C?

查看:151
本文介绍了计时器在C pthread的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线程,我需要定期做一些不同的时间间隔了一些工作,这将是做到这一点的好办法?睡眠(),然后我需要跟踪的间隔到下一个唤醒,这似乎并没有是最好的方式。

in threads, i need to periodically do some work in some different intervals, what would be a good way to do this? With sleep(), then i need keep track of the interval to the next wakeup, which doesn't seem to be the best way.

感谢。

推荐答案

您可以使用 clock_nanosleep TIMER_ABSTIME 标志与绝对时间,而不是相对时间为你的睡眠工作。这将避免误差积累的问题,你的程序被中断的比赛条件,并计划获取当前的时间之后,但在调用睡前另一个进程。

You can use clock_nanosleep with the TIMER_ABSTIME flag to work with absolute times instead of relative times for your sleep. That will avoid error accumulation problems and race conditions where your program gets interrupted and another process scheduled after getting the current time but before calling sleep.

另外,您可以使用POSIX计时器( timer_create )与信号处理程序,在您选择的信号被阻断在所有线程,但你的,或定时器交付新线程标志着一个条件变量或信号的线程正在等待。

Alternatively you could use POSIX timers (timer_create) with a signal handler, where the signal you choose is blocked in all threads but yours, or with timer delivery in a new thread that signals a condition variable or semaphore your thread is waiting on.

这篇关于计时器在C pthread的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆