我正在尝试在进行一些轮询的 C++ 方法中实现超时。该方法当前看起来像这样(没有超时):
do {
do_something();
usleep(50);
} while(!is_finished());
该解决方案应具有以下属性:
- 应该在系统时间的变化中幸存下来
- 以毫秒为单位的超时(一些抖动是可以接受的)
- POSIX 兼容
- 不应使用信号(是库的一部分,避免副作用)
- 可能会使用 Boost
I am currently thinking about using clock()
and do something like this:
start = clock();
do {
do_something();
usleep(50); // TODO: do fancy stuff to avoid waiting after the timeout is reached
if(clock() - start > timeout * CLOCKS_PER_SEC / 1000) break;
} while(!is_finished());
Is this a good solution? I am trying to find the best possible solution as this kind of task seems to come up quite often.
What is considered best practice for this kind of problem?
Thanks in advance!