From c0a2e2161d7c2c48aa3409401d59531f3714ff0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Lapeyre?= Date: Fri, 5 Jun 2020 15:48:16 +0200 Subject: [PATCH] Add multiprocessing.Lock.locked() --- Doc/library/multiprocessing.rst | 6 ++++++ Lib/multiprocessing/synchronize.py | 3 +++ Lib/test/_test_multiprocessing.py | 2 ++ .../next/Library/2020-06-05-15-47-43.bpo-40872.hW9afp.rst | 2 ++ 4 files changed, 13 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2020-06-05-15-47-43.bpo-40872.hW9afp.rst diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index 08258a65a89dc35..d92a359fbad69ac 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -1301,6 +1301,12 @@ object -- see :ref:`multiprocessing-managers`. Behavior is the same as in :meth:`threading.Lock.release` except that when invoked on an unlocked lock, a :exc:`ValueError` is raised. + .. method:: locked() + + Return true if the lock is acquired. + + .. versionadded:: 3.10 + .. class:: RLock() diff --git a/Lib/multiprocessing/synchronize.py b/Lib/multiprocessing/synchronize.py index 4fcbefc8bbefd33..e811d42a86f1976 100644 --- a/Lib/multiprocessing/synchronize.py +++ b/Lib/multiprocessing/synchronize.py @@ -161,6 +161,9 @@ class Lock(SemLock): def __init__(self, *, ctx): SemLock.__init__(self, SEMAPHORE, 1, 1, ctx=ctx) + def locked(self): + return self._semlock._is_zero() + def __repr__(self): try: if self._semlock._is_mine(): diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index d01a6680e409cb4..fb1f33ff376eb76 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -1230,8 +1230,10 @@ class _TestLock(BaseTestCase): def test_lock(self): lock = self.Lock() self.assertEqual(lock.acquire(), True) + self.assertTrue(lock.locked()) self.assertEqual(lock.acquire(False), False) self.assertEqual(lock.release(), None) + self.assertFalse(lock.locked()) self.assertRaises((ValueError, threading.ThreadError), lock.release) def test_rlock(self): diff --git a/Misc/NEWS.d/next/Library/2020-06-05-15-47-43.bpo-40872.hW9afp.rst b/Misc/NEWS.d/next/Library/2020-06-05-15-47-43.bpo-40872.hW9afp.rst new file mode 100644 index 000000000000000..0b2c3402484f8b0 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-06-05-15-47-43.bpo-40872.hW9afp.rst @@ -0,0 +1,2 @@ +:class:`multiprocessing.Lock` now has a `locked()` method that returns +whether the lock is currently held. Patch contributed by Rémi Lapeyre.