Issue #13502: threading: Fix a race condition in Event.wait() that made it
return False when the event was set and cleared right after.
diff --git a/Lib/test/lock_tests.py b/Lib/test/lock_tests.py
index 30148e6..094cc7a 100644
--- a/Lib/test/lock_tests.py
+++ b/Lib/test/lock_tests.py
@@ -351,6 +351,22 @@
         for r, dt in results2:
             self.assertTrue(r)
 
+    def test_set_and_clear(self):
+        # Issue #13502: check that wait() returns true even when the event is
+        # cleared before the waiting thread is woken up.
+        evt = self.eventtype()
+        results = []
+        N = 5
+        def f():
+            results.append(evt.wait(1))
+        b = Bunch(f, N)
+        b.wait_for_started()
+        time.sleep(0.5)
+        evt.set()
+        evt.clear()
+        b.wait_for_finished()
+        self.assertEqual(results, [True] * N)
+
 
 class ConditionTests(BaseTestCase):
     """
diff --git a/Lib/threading.py b/Lib/threading.py
index 043e6c8..fe92f10 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -418,9 +418,10 @@
     def wait(self, timeout=None):
         self._cond.acquire()
         try:
-            if not self._flag:
-                self._cond.wait(timeout)
-            return self._flag
+            signaled = self._flag
+            if not signaled:
+                signaled = self._cond.wait(timeout)
+            return signaled
         finally:
             self._cond.release()