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

Chris Angelico rosuav at gmail.com
Sat Sep 17 19:38:05 EDT 2011


On Sun, Sep 18, 2011 at 9:26 AM, Dennis Lee Bieber
<wlfraed at ix.netcom.com> wrote:
> def threadWork(lock, a1, a2, rate):
>        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()
>

It's obviously going to be an issue with killing processes too, which
is why database engines have so much code specifically to protect
against this. 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

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.

Obviously there won't be any problem with the Python interpreter
itself (refcounts etc) if the kill is done by exception - that would
be a potential risk if using OS-level kills.

ChrisA



More information about the Python-list mailing list