]> granicus.if.org Git - python/commitdiff
Accept optional lock object in Condition ctor (tulip issue #198)
authorAndrew Svetlov <andrew.svetlov@gmail.com>
Sat, 26 Jul 2014 14:54:34 +0000 (17:54 +0300)
committerAndrew Svetlov <andrew.svetlov@gmail.com>
Sat, 26 Jul 2014 14:54:34 +0000 (17:54 +0300)
Lib/asyncio/locks.py
Lib/test/test_asyncio/test_locks.py

index 8d9e3b4dd9ada43279299877865b5643a96463e9..574e3618f27a622d4719fd5b23b8154366b84c62 100644 (file)
@@ -255,14 +255,17 @@ class Condition:
     A new Lock object is created and used as the underlying lock.
     """
 
-    def __init__(self, *, loop=None):
+    def __init__(self, lock=None, *, loop=None):
         if loop is not None:
             self._loop = loop
         else:
             self._loop = events.get_event_loop()
 
-        # Lock as an attribute as in threading.Condition.
-        lock = Lock(loop=self._loop)
+        if lock is None:
+            lock = Lock(loop=self._loop)
+        elif lock._loop is not self._loop:
+            raise ValueError("loop argument must agree with lock")
+
         self._lock = lock
         # Export the lock's locked(), acquire() and release() methods.
         self.locked = lock.locked
index 8ad148634a21e263f6ac5146ede0444701848c41..c4e74e333038dc883d172e3d8368c0c8db9f1eab 100644 (file)
@@ -656,6 +656,18 @@ class ConditionTests(test_utils.TestCase):
 
         self.assertFalse(cond.locked())
 
+    def test_explicit_lock(self):
+        lock = asyncio.Lock(loop=self.loop)
+        cond = asyncio.Condition(lock, loop=self.loop)
+
+        self.assertIs(lock._loop, cond._loop)
+
+    def test_ambiguous_loops(self):
+        loop = self.new_test_loop()
+        lock = asyncio.Lock(loop=self.loop)
+        with self.assertRaises(ValueError):
+            asyncio.Condition(lock, loop=loop)
+
 
 class SemaphoreTests(test_utils.TestCase):