Skip to content
This repository has been archived by the owner on Feb 9, 2022. It is now read-only.

Commit

Permalink
Add the missing locked() interface
Browse files Browse the repository at this point in the history
threading.Lock has a little known locked() method, documented in
https://docs.python.org/2.6/library/thread.html#thread.lock.locked

This method is not very useful, but since pthreading.Lock must be
drop-in replacement for threading.Lock, we must implement it.

This patch adds the missing method, implementing it in the same way
Python implements it.  Since RLock does not have this method, RLock does
not extend Lock now.

Signed-off-by: Nir Soffer <nsoffer@redhat.com>
  • Loading branch information
bronhaim committed Jun 15, 2014
1 parent cefae77 commit b42f0ac
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
16 changes: 13 additions & 3 deletions pthreading.py
Expand Up @@ -51,9 +51,9 @@
import pthread


class Lock(pthread.Mutex):
class _Lock(pthread.Mutex):
"""
Lock class mimics Python native threading.Lock() API on top of
_Lock class mimics Python native threading.Lock() API on top of
the POSIX thread mutex synchronization primitive.
"""
def __enter__(self):
Expand All @@ -78,9 +78,19 @@ def release(self):
self.unlock()


class Lock(_Lock):
def locked(self):
# Yes, this is horrible hack, and the same one used by Python
# threadmodule.c. But this is part of Python lock interface.
if self.acquire(blocking=False):
self.release()
return False
return True


class RLock(Lock):
def __init__(self):
pthread.Mutex.__init__(self, recursive=True)
_Lock.__init__(self, recursive=True)


class Condition(object):
Expand Down
7 changes: 7 additions & 0 deletions tests.py
Expand Up @@ -60,6 +60,13 @@ def testAcquireRecursive(self):
self.assertTrue(lock.acquire())
self.assertTrue(lock.acquire(False))

def testLocked(self):
lock = pthreading.Lock()
self.assertFalse(lock.locked())
with lock:
self.assertTrue(lock.locked())
self.assertFalse(lock.locked())


class Flag(object):
def __init__(self):
Expand Down

0 comments on commit b42f0ac

Please sign in to comment.