Implementing locking with Python Classes

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


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

	def create(self, dictRequest):
			#-- Acquire lock initially so that the release statement doesn't fail in the finally section
			#-- 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
			#-- 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

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() # this will block

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

To read more about RLock() –


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s