[Python-3000] threading, part 2

Josiah Carlson jcarlson at uci.edu
Fri Aug 11 17:45:54 CEST 2006


Slawomir Nowaczyk <slawomir.nowaczyk.847 at student.lu.se> wrote:
> I believe that if asynchronous exception raising ever gets officially
> approved, there absolutely *needs* to be a way to block it for a piece
> of code that should execute atomically.

There is already a way of making Python source execution atomic with
respect to other Python code [1].


> But it should not be done lightly and never when the code is not
> specifically expecting it.

If you don't want random exceptions being raised in your threads, then
don't use this method that is capable of raising exceptions somewhat
randomly.

 - Josiah

[1]
Remove the two sys.setcheckinterval calls to verify this works.
"proper" use should probably use try/finally wrapping.

>>> import sys
>>> import threading
>>> import time
>>>
>>> x = 0
>>>
>>>
>>> def thr(n):
...     global x
...     while not x:
...         time.sleep(.01)
...     for i in xrange(n):
...         sys.setcheckinterval(sys.maxint)
...         _x = x + 1
...         x, _x = _x, x
...         sys.setcheckinterval(100)
...
>>>
>>> for i in xrange(10):
...     threading.Thread(target=thr, args=(1000000,)).start()
...
>>> x += 1
>>> while threading.activeCount() > 1:
...     time.sleep(.1)
...
>>> print x
10000001
>>>



More information about the Python-3000 mailing list