How to terminate the function that runs every n seconds

Marko Rauhamaa marko at pacujo.net
Thu Jan 15 16:29:43 CET 2015


Marko Rauhamaa <marko at pacujo.net>:
> Dennis Lee Bieber <wlfraed at ix.netcom.com>:
>> 	My response to that then is: design the thread's I/O so that it
>> is not blocking... On Linux, maybe a timed select(); Windows? short
>> sleeps around a non-blocking check for available data... (if console
>> I/O, msvcrt.kbhit(); otherwise may need some other library function to
>> put a time-out on the I/O)
>
> Ah, polling, the fig leaf that covers embarrassing design constraints
> all over the world.

And to provide something constructive, I should add:

Polling is occasionally the right way forward (consider the Linux
kernel's NAPI, for example). However, it is usually bad because:

 * it consumes resources when there is no need: the CPU wakes up from
   the power-saving mode, the hard disk spins unnecessarily; the battery
   that should be good for several years, dies in the middle of the
   winter

 * it is not reactive enough as you must wait patiently for the polling
   interval to expire.


Since you brought up select(), a better choice is right under your nose:
multiplexing. Have your program block and be prepared for any possible
stimulus. However, once you do that, you realize you lose the naive
simplicity of threads. Thus we arrive at the conclusion: asynchronous
programming and processes are usually a better design choice than
threads.


Marko



More information about the Python-list mailing list