thammi
thammi

Reputation: 454

Best practice for self made timeout

I am trying to implement a timeout in a C++ method which does some polling. The method currently looks like this (without timeout):

do {
    do_something();
    usleep(50);
} while(!is_finished());

The solution should have the following properties:

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!

Upvotes: 1

Views: 323

Answers (2)

Jens Gustedt
Jens Gustedt

Reputation: 78903

clock is not the right choice if you want to be portable. On conforming systems this is the CPU time used by your process, on windows it seems to be wall clock time. Also usleep is obsolete in current POSIX and you are supposed to use nanosleep.

There is one method that could be suitable for a wider range of platforms, select. This call has a fifth argument that let's you place a timeout. You can (mis)use that, to wait for network events that you know will never happen, and that then will timeout after a controlled amount of time. From the linux manual on that:

Some code calls select() with all three sets empty, nfds zero, and a non-NULL timeout as a fairly portable way to sleep with subsecond precision.

Upvotes: 1

6502
6502

Reputation: 114461

A timeout precise to milliseconds is out of the reach of any OS that doesn't specifically provide realtime support.

If your system is under heavy load (even temporarily) it's quite possible to have it unresponsive for seconds. Sometimes standard (non-realtime) systems can become very unresponsive for apparently stupid reasons like accessing a CD-Rom device.

Linux has some realtime variations, while for Windows IIRC the only realtime solutions actually have a realtime kernel that is managing the hardware on which a Windows system is run basically "emulated" in a virtual machine.

Upvotes: 1

Related Questions