Skip to content

Commit fd1bdcd

Browse files
committed
Prove serialization with a barrier instead of a sleep
A sleep inside the transaction only makes an overlap likely to be observed. A barrier both threads must reach while inside can be satisfied only if they are genuinely there together, so the assertion means what it says -- and removing the lock makes it fail, which was checked.
1 parent e2b0430 commit fd1bdcd

1 file changed

Lines changed: 16 additions & 12 deletions

File tree

‎tests/test_terminal_transaction.py‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -278,28 +278,32 @@ def worker() -> None:
278278

279279
class TestSerialization:
280280
def test_two_threads_never_hold_the_terminal_at_once(self) -> None:
281-
"""The lock is what serializes emission; without it the two bodies overlap."""
281+
"""The lock is what serializes emission; without it the two bodies meet.
282+
283+
The overlap is detected with a barrier rather than a sleep. A sleep would only make
284+
an overlap *likely* to be observed; a barrier that both threads must reach inside the
285+
transaction can only be satisfied if they are genuinely inside it together.
286+
"""
282287
terminal = TerminalLock()
283-
overlaps = 0
284-
inside = 0
285-
entered = threading.Barrier(2, timeout=5)
288+
both_inside = threading.Barrier(2, timeout=0.2)
289+
start = threading.Barrier(2, timeout=5)
290+
overlaps: list[int] = []
286291

287292
def emit() -> None:
288-
nonlocal overlaps, inside
289-
entered.wait()
293+
start.wait()
290294
with terminal.transaction("paint"):
291-
if inside:
292-
overlaps += 1
293-
inside += 1
294-
time.sleep(0.01)
295-
inside -= 1
295+
try:
296+
both_inside.wait()
297+
except threading.BrokenBarrierError:
298+
return
299+
overlaps.append(1)
296300

297301
threads = [threading.Thread(target=emit) for _ in range(2)]
298302
for thread in threads:
299303
thread.start()
300304
for thread in threads:
301305
thread.join(timeout=5)
302-
assert overlaps == 0
306+
assert overlaps == []
303307

304308

305309
class TestDiagnostics:

0 commit comments

Comments
 (0)