Precise Timer Queues in C++ - c++

I'm developing an application that needs to send out messages at specific times (it's to do with multimedia so the timing precision is important), so effectively I need a mechanism to call a callback function in a specified number of milliseconds.
I need to support both Windows and Mac OS X. I've looked into Timer Queues on Windows which looks like what I need, but I have read that the timing precision is just not precise enough for multimedia based applications (my application is sensing MIDI messages to a driver at specific times). Any ideas?

I think your best bet on Windows is to use Multimedia Timers. On OS X, the simplest function to use would be nanosleep, but you can go a long way with kqueue. I don't think there will be any problems if you are talking milliseconds precision (a millisecond is a very, very long time). The only thing you will possibly need to do is to make sure OS runs your process as "real-time".

Any sleep function is 'a least' with all OS that I know of.
If theat OS has a lot of tasks it is up to the scheduler for those tasks.
In space they have dedicate hardware that does simple functions from a queue - that is the best you can get - and they are not croweded

Related

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:
should survive changes of the system time
timeout in milliseconds (some jitter is acceptable)
POSIX compatible
should not use signals (is part of a library, avoid side effects)
might use 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!
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.
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.

Why should I use the SetTimer function instead of multimedia timer services for applications not requiring high resolution timing?

Why should I use the SetTimer function instead of multimedia timer services for applications that do not use high-resolution timing?
According to the official documentation that's what I should do, with no reason given as to why.
Higher-resolution timing is less efficient. The OS needs to keep track of time more accurately, and it may need to suspend other threads at inefficient times to get your timer called on time. So basically, high resolution timers are expensive, and you should only use expensive things when you need to.
In addition to Brendan's point, with SetTimer you get a Windows message that fits directly into the architecture of a GUI program, with no interthread communication required. With the multimedia timers, you get a callback on a system thread, which is awkward to integrate and synchronize with the code running on your thread(s).

Delaying for milliseconds in C++ cross-platform

I'm writing a multi-platform internal library in C++ that will eventually run on Windows, Linux, MacOS, and an ARM platform, and need a way to sleep for milliseconds at a time.
I have an accurate method for doing this on the ARM platform, but I'm not sure how to do this on the other platforms.
Is there a way to sleep with millisecond resolution on most platforms or do I have to special-case things for each platform?
For Linux and Mac OS X you can use usleep:
usleep(350 * 1000);
For Windows you can use Sleep:
Sleep(350);
EDIT: usleep() sleeps for microseconds, not milliseconds, so needs adjusting.
boost::this_thread::sleep()
usleep provides microsecond resolution theoretically, but it depends on platform.
It seems to be obsolete on windows, so you should use QueryPerformanceCounter there (or write your compatibility layer).
P.S.: building program depending on sleeps is often a way to disaster. Usually, what programmer really wants is waiting for some event to happen asynchronously. In this case you should look at waitable objects available at the platform, like semaphores or mutexes or even good ol' file descriptors.
for timer you could use boost asio::deadline_timer, synchronously or asynchronously.
you also could look into boost::posix_time for timer precision adjustment between seconds,milliseconds,microseconds and nanoseconds.
Windows sleep() does provide millsecond precision, but nowhere near millisecond accuracy. There is always jitter, especially with small values on a heavily-loaded system. Similar problems are only to be expected with other non-real-time OS. Even if the priority of the thread calling sleep() is very high, a driver interrupt may introduce an extra delay at any time.
Rgds,
Martin

How does a scheduler end a running process?

I just realized that after learning a lot about various scheduling algorithms, how a context switch is done, etc. one thing still isn't clear to me.
Take a uniprocessor system:
If process A is running and it's time slot should end in 5 seconds, how does the scheduler or the operating system know how to end it after 5 seconds? No part of the operating system can run while A is running. The scheduler is supposed to be monitoring it, but how can it if it cannot run? Does the operating system's scheduler write an ISR and have an interrupt generate every 5 seconds? Is this possible? Even if it is, it doesn't seem a good way to implement it.
How exactly does a scheduler do this?
Does the operating system's scheduler write an ISR and have an interrupt generate every 5 seconds? Is this possible? Even if it is, it doesn't seem a good way to implement it.
Yes, this is exactly how it works on a preemptive multitasking system (although on desktop systems the interval is usually more like 10 milliseconds).
Yes, there are other schemes, such as cooperative multitasking, where each process decides for itself when to yield.
Yes, normally there is some kind of timer interrupt that fires. The kernel can then run for a bit and switch process context if it needs to - normally that interrupt would fire an awful lot more often than just once every 5 seconds though. Why doesn't it seem like a good way to implement it?

What is the official way to call a function (C/C++) in ab. every 1/100 sec on Linux?

I have an asynchronous dataflow system written in C++. In dataflow architecture, the application is a set of component instances, which are initialized at startup, then they communicate each other with pre-defined messages. There is a component type called Pulsar, which provides "clock signal message" to other components which connect to one it (e.g. Delay). It fires message (calls the dataflow dispatcher API) every X ms, where X is the value of the "frequency" parameter, which is given in ms.
Short, the task is just to call a function (method) in every X ms. The question is: what's the best/official way to do it? Is there any pattern for it?
There are some methods I found:
Use SIGALRM. I think, signalling is not suits for that purpose. Altough, the resolution is 1 sec, it's too rare.
Use HW interrupt. I don't need this precisity. Also, I aware using HW-related solution (the server is compiled for several platforms, e.g. ARM).
Measure elapsed time, and usleep() until next call. I'm not sure that it's the best way to measure time to call time related system calls by 5 thread, each 10 times in every second - but maybe I'm wrong.
Use RealTime kernel functions. I don't know anything about it. Also, I don't need crystal precise call, it's not an atomreactor, and I can't install RT kernel on some platforms (also, 2.6.x Kernel is available).
Maybe, the best answer is a short commented part of an audio/video player's source code (which I can't find/understand by myself).
UPDATE (requested by #MSalters): The co-author of the DF project is using Mac OSX, so we should find a solution that works on most Posix-compilant op. systems, not only on Linux. Maybe, in the future there'll be a target device which uses BSD, or some restricted Linux.
If you do not need hard real-time guarantees, usleep should do the job. If you want hard real-time guarantees then an interrupt based or realtime kernel based function will be necessary.
To be honest, I think having to have a "pulsar" in what claims to be an asynchronous dataflow system is a design flaw. Either it is asynchronous or it has a synchronizing clock event.
If you have a component that needs a delay, have it request one, through boost::asio::deadline_timer.async_wait or any of the lower level solutions (select() / epoll() / timer_create() / etc). Either way, the most effective C++ solution is probably the boost.asio timers, since they would be using whatever is most efficient on your linux kernel version.
An alternative to the previously mentioned approaches is to use the Timer FD support in Linux Kernels 2.6.25+ (pretty much any distribution that's close to "current"). Timer FDs provide a bit more flexibility than the previous approaches.
Neglecting the question of design (which I think is an interesting question, but deserves its own thread)...
I would start off by designing an 'interrupt' idea, and using signals or some kernel function to interrupt every X usec. I would delay doing sleep-functions until the other ideas were too painful.