Reputation: 2332
I have a thread that eventually will get its data from a sensor every 1ms and does some processing which should take less than 1ms (say 0.5ms). For the moment I wish to simulate the sensor using another thread. So my goal is to have a thread that generates data every 1ms and sends it to another thread. Lets assume generating and sending times are negligible.
I tried using this_thread::sleep_for
but it didn't work well. I got basically random sleeping time anywhere between 1ms and 15ms. I think I can use chrono::high_resolution_clock
. But that would require busy wait.
Any other ideas?
I can settle for an average of 1ms provided that in no case it is less than the processing time.
Upvotes: 0
Views: 2239
Reputation: 1
Do you just want to sleep for intervals less than 1ms? Have you tried usleep() (unistd.h) or nanosleep() (time.h)? There might be some jitter due to scheduling imprecisions --- if this is not acceptable, you need to resort to a spin loop.
Upvotes: 0
Reputation: 1319
On Windows, you can request a custom timer resolution with the timeBeginPeriod()
call (see this example). You'll probably still want to test to see how close it actually gets you to 1 ms, though.
Also bear in mind that even busy-wait isn't a surefire solution here. If the CPU is under sufficient load, there's no guarantee that your program will get execution time within any given 1-millisecond slice.
Upvotes: 0
Reputation: 57678
I recommend setting up a timer for 1 millisecond reload and using the interrupt vector for the timer.
On the embedded system I'm working on, we a have a 1ms timer tick ISR. We have tweaked the hardware to get this as accurate as possible (including using oscilloscopes for measurement).
You may want to make it the highest priority interrupt or task.
The processor we use comes with several timers. When the timer expires, it can execute code as an interrupt.
Upvotes: 0
Reputation: 31457
One millisecond is way below the normal scheduling threshold of most operating systems. Don't expect to be able to get two processes or threads to interact reliably with that frequency. On Linux, for example, the scheduler timeslice is usually 100ms by default (although it can be lower, but don't expect less than 10ms).
Upvotes: 0
Reputation: 19118
If you don't mind wasting processing power, use busy wait: spin until the millisecond elapses:
auto start = std::chrono::high_resolution_clock::now();
auto now = start;
while (not_ready(start, now))
{
now = std::chrono::high_resolution_clock::now();
}
Upvotes: 1