The problem with using threads for this is that there will be a propagation delay between the controlling thread deciding it is time to issue a pulse and the writing thread receiving the command to write. And that delay will be non-determanistic.
Once the controller issues the write command--however it does that--it will then have to relinquish the rest of its time-slice. At that point you are in the hands of the system scheduler as to when the write thread will next be run. It might choose it immediately, but it is very unlikely on a system that has many other threads running--device drivers; system processes; and other application programs. There would simply be no way to know how long it would be before the other thread got the command.
You might set the write thread to a real-time priority setting, which would mean it would get a look in before most other threads. But some device drivers and system processes will also run at real-time priority and you would be competing with them. I don't think that threads are of much advantage here--not as you've described using them anyway.
For example, on my system, even when I am watching a video and playing an mp3, the following code hits the 500 millisecond target to within 1 or 2 milliseconds every time:
#! perl -slw
use strict;
use Time::HiRes qw[ time sleep ];
my $next = time() + 0.5;
while( 1 ) {
sleep .001 while time() < $next;
printf "%10.3f\n", time();
$next += 0.5;
}
__END__
c:\test>849367
1279055103.020
1279055103.520
1279055104.020
1279055104.519
1279055105.020
1279055105.520
1279055106.019
1279055106.520
1279055107.020
1279055107.519
1279055108.020
1279055108.519
1279055109.020
1279055109.519
1279055110.020
1279055110.519
1279055111.020
I do have multiple cpus though. YMMV on a single cpu system.
In fact, with a small tweak, it hits it to the millisecond every time at the expense of a fraction more cpu (still < 1% though) even with two video streams playing:
#! perl -slw
use strict;
use Time::HiRes qw[ time sleep ];
my $next = time() + 0.5;
while( 1 ) {
sleep .001 while time() < ( $next - 0.01 );
1 while time() < $next;
printf "%10.4f\n", time();
$next += 0.5;
}
__END__
c:\test>849367
1279056441.7570
1279056442.2570
1279056442.7570
1279056443.2570
1279056443.7570
1279056444.2570
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|