3

In my application there is a Linux thread that needs to be active every 10 ms, thus I use usleep (10*1000). Result: thread never wakes up after 10 ms but always after 20 ms. OK, it is related to scheduler timeslice, CONFIG_HZ etc. I was trying to use usleep(1*1000) (that is 1 ms) but the result was the same. Thread always wakes up after 20 ms.

But in the same application the other thread handles network events (UDP packets) that came in every 10 ms. There is blocking 'recvfrom' (or 'select') and it wakes up every 10 ms when there is incoming packet. Why it is so ? Does select has to put the thread in 'sleep' when there are no packets? Why it behave differently and how can I cause my thread to be active every 10 ms (well more or less) without external network events?

Thanks, Rafi

Rafi
  • 161
  • 5

1 Answers1

3

You seem to be under the common impression that these modern preemptive multitaskers are all about timeslices and quantums.

They are not.

They are all about software and hardware interrupts, and the timer hardware interrupt is only one of many that can set a thread ready and change the set of running threads. The hardware interrupt from a NIC that causes a network driver to run is an example of another one.

If a thread is blocked, waiting for UDP datagrams, and a datagram becomes avaialable because of a NIC interrupt running a driver, the blocked thread will be made ready as soon as the NIC driver has run because the driver will signal the thread and request an immediate reschedule on exit. If your box is not overloaded with higher-rpiority ready threads, it will be set running 'immediately' to handle the datagram that is now available. This mechanism provides high-performance I/O and has nothing to do with any timers.

The timer interrupt runs periodically to support sleep() and other system-call timeouts. It runs at a fairly low frequency/high interval, (like 1/10ms), because it is another overhead that should be minimised. Running such an interrupt at a higher frequency would reduce timer granularity at the expense of increased interrupt-state and rescheduling overhead that is not justified in most desktop installations.

Summary: your timer operations are subject to 10ms granularity but your datagram I/O responds quickly.

Also, why does you thread need to be active every 10ms? What are you polling for?

Martin James
  • 24,453
  • 3
  • 36
  • 60
  • I want to poll the USB headset for the 10 ms audio frames. I'm doing it with ALSA APIs. ALSA (on my hardware) fails to provide me accurate 10 ms frames but is able to give 20 ms frames. These frames need to be passed to DSP that is able to accept only 10 ms frames (small buffer). Thus I want to store the 20 ms frames in one thread and feed the DSP with 10 ms frames from the other thread. – Rafi May 20 '14 at 12:11