thread conditional code

Tim Peters tim.one at home.com
Sat Apr 14 07:16:19 EDT 2001


[Robin Becker]
> It seems that using a lock requires the threading overhead;
> so is there any way to avoid locking when threading hasn't been
> started?

I'm sure that if you try this again, you'll be able to find a coherent
question in there somewhere <wink>.

> I guess I would like to know if thread.c's initialized variable
> is true / false.

It starts life as 0 and remains 0 unless and until you import thread.  So
sys.modules.has_key("thread") should do the trick.  That someone imported
thread doesn't mean another thread exists, though; also that someone did not
import thread doesn't mean another thread doesn't exist (e.g., foreign
threads can call back into Python, if they do the right dance, and importing
thread isn't part of that dance).

> That way I could conditionally lock access to contentious
> variables and avoid thread overhead when not needed.

I'm afraid the only way to be sure of that is to build Python without
threads -- only the OS knows how many threads exist at any given time.  If
it's *possible* for another thread to pop into existence in your Python code,
then you have to lock even before it pops into existence, lest it pop into
existence "in the middle" of one of your critical sections that you cleverly
avoided locking, and then enter the (unlocked) critical section at the same
time.  If the threads you deal with are too well behaved for that, then
there's no need for any locks at all <wink>.

trying-to-cheat-locks-is-the-#1-cause-of-thread-disasters-ly y'rs  - tim





More information about the Python-list mailing list