Critical sections and mutexes

David Bolen db3l at fitlinxx.com
Thu Oct 25 00:28:15 EDT 2001


<brueckd at tbye.com> writes:

> That's true either way. With a very few multithreaded Python apps under
> your belt it gets so that it doesn't take too many brain cycles to
> recognize the GIL-does-this-for-free scenarios. Yes, you can always
> overengineer a solution if you want, but that's not very Pythonic.

The GIL doesn't do much for free for me in terms of controlling access
to my shared resources within my application, given that my code can
be interrupted between any two bytecodes and moved to a separate
thread.  Sure there are some pure producer/consumer scenarios that are
safe, but they're safe in any language, with or without a GIL, to some
level of granularity.  (E.g., even in C, a producer consumer of a
shared integer can be considered the same level of safety we're
talking about here).

If you're able to make assumptions in applications and get away with I
certainly won't stop you from writing that way, but with more than a
few multithreaded applications in more than a few languages/systems
under my belt, I've learned it's always better to be safe than sorry
in multithreaded programs.

> Think of it this way: the way the GIL works can impose a slight
> performance hit on your program (a cost). With that cost is an associated
> benefit. You can choose whether or not to enjoy that benefit, but you've
> already paid the cost so you might as well.

But the GIL does nothing for application-specific shared resources.
It only protects the interpreter, so that, as you mentioned in another
response, a normal Python script can't crash the interpreter.  It does
nothing to prevent application-specific data structures from becoming
corrupt and affecting the behavior of the application.

At the very least, for anyone just getting into multithreaded
programming, it can be dangerous to think it guarantees anything else.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list