Implementing locking with Python Classes

Implementing locking mechanism is straightforward in Python – given you handle the exceptions well.

#!/usr/bin/python

class Account(object):
	#Managing accounts
	__getAcctLock = threading.RLock()

	def create(self, dictRequest):
		try:
			#-- Acquire lock initially so that the release statement doesn't fail in the finally section
			Account.__getAcctLock.acquire()
			#-- Query the Account table for existence of account -- Create new if it doesn't exist
			#-- Do other stuff here for account creation
		except Exception:
			#-- Handle exception
		finally:
			#-- Important to release the lock in finally block so we ensure that the lock is always released whether or not the code succeeded or failed
			Account.__getAcctLock.release()

Re-Entrant Locks (RLock)

The RLock class is a version of simple locking that only blocks if the lock is held by another thread. While simple locks will block if the same thread attempts to acquire the same lock twice, a re-entrant lock only blocks if another thread currently holds the lock. If the current thread is trying to acquire a lock that it’s already holding, execution continues as usual.

lock = threading.Lock()
lock.acquire()
lock.acquire() # this will block

lock = threading.RLock()
lock.acquire()
lock.acquire() # this won’t block

To read more about RLock() – http://effbot.org/zone/thread-synchronization.htm.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s