Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is RLock a sensible default over Lock?

the threading module in Python provides two kinds of locks: A common lock and a reentrant lock. It seems to me, that if I need a lock, I should always prefer the RLock over the Lock; mainly to prevent deadlock situations.

Besides that, I see two points, when to prefer a Lock over a RLock:

  • RLock has a more complicated internal structure and may therefore have worse performance.
  • Due to some reason, I want to prevent a thread recursing through the lock.

Is my reasoning correct? Can you point out other aspects?

like image 918
Bernhard Kausler Avatar asked Nov 30 '09 21:11

Bernhard Kausler


1 Answers

Two points:

  • In officially released Python versions (2.4, 2.5... up to 3.1), an RLock is much slower than a Lock, because Locks are implemented in C and RLocks in Python (this will change in 3.2)
  • A Lock can be released from any thread (not necessarily the thread which acquire()d it), while an RLock has to be released by the same thread which acquired it

Bottom line, I'd suggest to only use an RLock if it matches the semantics you are looking for, otherwise stick to Locks by default.

like image 149
Antoine P. Avatar answered Oct 12 '22 15:10

Antoine P.