python threads and the linuxthread pthread library

Tim Peters tim.one at comcast.net
Mon Jul 1 15:42:15 EDT 2002


[anton wilson]
> ...
> However, I am a bit confused on how threads interact with the python
> interpreter at a low level.

In general, if you have N threads, at any given time one of those threads is
holding the GIL (global interpreter lock), and the other N-1 threads are
blocked trying to acquire the GIL.  No more than one thread can be running
in the PVM at a time.  A C module that knows for certain it won't be running
the PVM can release the GIL to do some work in C (or Fortran, whatever),
allowing some other thread to run in the PVM while it's doing its C
(whatever) work.  The Python implementation routinely does this around
potentially blocking C-level I/O operations.

> Is the Python Virtual Machine it's own thread?

No.  All threads run in the PVM, but the GIL serializes their PVM time.

> How do threads aquire the global interpreter lock once they are awoken?

I'm not sure what you mean by "awoken".  Python doesn't normally put threads
to sleep <wink>.  Threads that don't hold the GIL are normally blocked
trying to acquire the GIL.  If by "awoken" you mean "become unblocked", then
awakening and acquiring the GIL are exactly the same thing -- one doesn't
precede the other.  The details of how the GIL gets acquired live inside
your platform thread implementation.  On Linux, Python may use either
pthread condition variables, or POSIX semaphores, to implement the GIL.

> How exactly do the byte-codes for a particular thread get run by the
> Python interpreter?

See ceval.c.  This isn't a thread issue beyond that threads in the PVM are
serialized by the GIL.

> Does each thread run the interpreter?

Yes, but they're serialized via the GIL.






More information about the Python-list mailing list