simple Thread question
Christopher T King
squirrel at WPI.EDU
Tue Aug 3 16:05:40 EDT 2004
On 3 Aug 2004, adeger wrote:
> Having trouble with my first forays into threads. Basically, the
> threads don't seem to be working in parallel (or you might say are
> blocking). I've boiled my problems to the following short code block
> and ensuing output. Seems like the output should be all interleaved
> and of course it's not. Running Python 2.2 from ActiveState on
> Windows XP (also doesn't work on Windows 2000).
The Python interpreter isn't too thread-friendly. Because it's not
re-entrant, it has to make use of a Global Interpreter Lock in order to
keep internal structures from getting mangled. This lock only allows one
thread to access the interpreter at a time, and switches threads every
hundred or so bytecodes. The likely cause of your problem is that your
loops don't reach this switching threshold -- try using xrange(100) or
higher.
The GIL is released during blocking I/O (or other) operations, and C
extensions can release the lock if they plan on doing lots of non-Python
processing. Because of the former property, another thing you can try is
inserting a time.sleep(.1) inside of each loop -- being a blocking I/O
operation, this should cause the GIL to be released, and your threads will
switch each time through the loop.
Aside from the performance loss on parallel-processing machines, there is
usually no reason to worry about the GIL in Python code: so long as you
make proper use of the thread synchronization routines, everything will
work as you intend it to.
More information about the Python-list
mailing list