Critical sections and mutexes

David Bolen db3l at
Thu Oct 25 00:49:37 CEST 2001

<brueckd at> writes:

> I was merely responding to somebody's not-entirely-true assertion that
> "_every_ access to that [shared] resource _must_ be enclosed in locks".

But that statement is more true than not (as other respondents have
shown, even a simple assignment may be an issue), and certainly it's
much smarter when writing threaded code to behave as if it were always
true, since the potential consequences when it isn't can be very

There are some cases (e.g., when performing read-only access to a
value where it isn't critical if the value changes and you just get
one of the two potential values, such as when watching a sentinel that
you'll just pick up on the next loop), but you really do need to
consider all possible users of every shared resource.

> P.S. - Print statements are not atomic and do not fall in the same realm
> as "normal" Python operations (e.g. "i = 5") because 'print' involves
> a potentially blocking access to an external resource (stdout). To avoid
> blocking the interpreter releases its global lock before writing to a file
> descriptor and reaquires it when done.

While the GIL is released around external I/O, even if that weren't
the case, a 'print' could be interrupted simply because it requires
multiple bytecodes, and the regular interruption at every 'n'
bytecodes could occur in the middle of the overall print processing.

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

More information about the Python-list mailing list