Killing threads (was Re: Cancel or timeout a long running regular expression)

Ian Kelly ian.g.kelly at gmail.com
Mon Sep 19 07:41:29 CEST 2011


On Sat, Sep 17, 2011 at 5:38 PM, Chris Angelico <rosuav at gmail.com> wrote:
> But if it's done as an exception, all you need is to
> catch that exception and reraise it:
>
> def threadWork(lock, a1, a2, rate):
>   try:
>       while True:
>               time.sleep(rate)
>               lock.lock()
>               t = a2.balance / 2
>               a1.balance += t
>               #say a thread.kill kills at this point
>               a2.balance -= t
>               lock.release()
>  except:
>      # roll back the transaction in some way
>      lock.release()
>      raise

And what if the thread gets killed a second time while it's in the except block?

> It'd require some care in coding, but it could be done. And if the
> lock/transaction object can be coded for it, it could even be done
> automatically:
>
> def threadWork(lock, a1, a2, rate):
>       while True:
>               time.sleep(rate)
>               transaction.begin()
>               t = a2.balance / 2
>               transaction.apply(a1.balance,t)
>               #say a thread.kill kills at this point
>               transaction.apply(a2.balance,-t)
>               transaction.commit()
>
> If the transaction object doesn't get its commit() called, it does no
> actions at all, thus eliminating all issues of locks.

And what if the thread gets killed in the middle of the commit?

Getting the code right is going to be a lot more complicated than just
adding a couple of try/excepts.

Cheers,
Ian



More information about the Python-list mailing list