thread conditional code

Tim Peters tim.one at home.com
Sat Apr 14 17:10:41 EDT 2001


[Robin Becker]
> if only one (the main) thread exists at the beginning of my critical
> section and I'm not creating any threads how could one pop into
> existence?

It depends on the context of your Python code, which I can't guess.  It's
quite possible for a foreign thread to call into Python, where "foreign" ==
an OS thread not created via Python's thread module.  This is probably
unusual under Linux, but common for some *kinds* of Python apps on Windows.
I don't know enough about what you're doing to guess.  But if you have total
control over all threads that may pop up in your app, I couldn't guess why
you were looking for low-level hooks either:  if you have total control over
threads, you have (or can have) total knowledge of the thread situation too.

> If python threads aren't initialised and I don't do the initialisation
> who else can do it?

Any thread whatsoever, known to Python or not, known to you or not, depending
on the context of your app.  If your app doesn't support any form of threaded
callback, this probably isn't an issue for your app.

> What I'm really asking is how to avoid initialising the threading
> checks without losing the possibility of locking.

What are "threading checks"?

> I assumed probably wrongly that there is an overhead to running
> multiple threads because of the ceval thread switch tests; after
> scanning the source code I suspect you have the thread switch
> overhead whether or not the thread stuff is initialized and then
> it makes no sense to avoid using it.

The periodic eval-loop "ticker checks" occur even if you compile Python
without thread support.  So there is no way to avoid *that* "overhead".
Fiddling with the global interpreter lock is just one of the things done
inside the ticker-check block.  But when Python starts running, ceval.c's
static interpreter_lock pointer is NULL, and the thread-switching code is
skipped so long as it remains NULL.  The only way it can become non-NULL is
if PyEval_InitThreads() gets called.  Python calls that itself when starting
a new thread, and calling it is part of the dance foreign threads have to do
if they want to call a Python C API function.  That's it.  Importing the
thread or threading modules does *not* make it non-NULL, and neither does,
e.g., allocating or even using (.release(), .acquire()) thread locks.  So the
thread-switch jitterbug does not occur until Python knows that at least two
threads exist.





More information about the Python-list mailing list