|
the thpinfo.com blogger archives (2007-2008) Threading and LocksPublished: 2007-08-09T21:05:00.001+02:00
Tags: threads, lock, python, threading
This week, I've been bitten by a dead-lock bug in my website's code twice already, and I've decided to fix it, and to write about it, as it seems like a common problem when starting with threading. To use a thread lock in Python, the threading module provides a def do_something(): The problem is, that if do_threadunsafe_operation() raises an exception, the lock will not be released, and therefore, all subsequent calls to do_something() will lock forever. You have to put the code in a try..finally block to make sure the lock gets released when the function ends:def do_something(): In the Python Cookbook, there is also a decorator version of this, so when using Python 2.4 and above, and you like using decorators, try the sychronized decorator and "decorate" your function: @synchronized(lo) Threads in Python are cool, and if you're careful using them, you can make your application run faster without affecting the stability or flow of your application. A lesson I learned last weekend when a bug with locking resulting in my WSGI app dead-locking and the website unreacheable. CommentsMike (2007-08-17T05:56:00.000+02:00) Thomas Perl (2007-08-10T11:37:00.000+02:00) illume (2007-08-10T03:47:00.000+02:00) Chris (2007-08-09T23:29:00.000+02:00) Thomas Perl (thp at this domain); jabber: thp@jabber.org |
|