Using threads for audio computing?

Sturla Molden sturla.molden at gmail.com
Wed May 14 10:23:57 EDT 2014


On 12/05/14 07:33, lgabiot wrote:

> But AFAIK the python GIL (and in smaller or older computers that have
> only one core) does not permit true paralell execution of two threads. I
> believe it is quite like the way multiple processes are handled by an OS
> on a single CPU computer: process A has x CPU cycles, then process B has
> y CPU cycles, etc...

Python threads are native OS threads. The GIL serializes access to the 
Python interpreter.

If your thread is waiting for i/o or running computations in C or 
Fortran (e.g. with NumPy), it does not need the Python interpreter.

Scientists and engineers use Python threads for "true parallel 
processing" all the time. The FUD you will find about the GIL is written 
by people who don't fully understand the issue.


> So in my case, I must have a way to make sure that:
> thread 1 (which gets audio from Pyaudio and put() it in the Queue) is
> not interrupted long enough to miss a sample.

Here you are mistaken. The DMA controller takes care of the audio i/o. 
Your audio acquisition thread is asleep while its buffer fills up. You 
don't miss a sample because your thread is interrupted.

You do, however, have to make sure your thread don't block on the write 
to the Queue (use block=False in the call to Queue.put), but it is not a 
"GIL issue".

In your case you basically have on thread waiting for the DMA controller 
to fill up a buffer and another doing computations in NumPy. Neither 
needs the GIL for most of their work.

If you are worried about the GIL you can always use processes 
(multiprocessing, subprocess, or os.fork) instead of threads.

Sturla













More information about the Python-list mailing list