Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

fix: keep rwlock ownership when acquisition is interrupted (#7944)

leilei316742ae4bf2c05f
diff --git a/lib/crewai/src/crewai/utilities/rw_lock.py b/lib/crewai/src/crewai/utilities/rw_lock.py
index 2c170b3d4..5b3d3cb8e 100644
--- a/lib/crewai/src/crewai/utilities/rw_lock.py
+++ b/lib/crewai/src/crewai/utilities/rw_lock.py
@@ -48,8 +48,8 @@ class RWLock:
Yields:
None
"""
+ self.r_acquire()
try:
- self.r_acquire()
yield
finally:
self.r_release()
@@ -74,8 +74,8 @@ class RWLock:
Yields:
None
"""
+ self.w_acquire()
try:
- self.w_acquire()
yield
finally:
self.w_release()
diff --git a/lib/crewai/tests/utilities/events/test_rw_lock.py b/lib/crewai/tests/utilities/events/test_rw_lock.py
index 27ebaf1d3..bbd0bfabd 100644
--- a/lib/crewai/tests/utilities/events/test_rw_lock.py
+++ b/lib/crewai/tests/utilities/events/test_rw_lock.py
@@ -5,6 +5,7 @@ This module tests the RWLock class for correct concurrent read and write behavio
import threading
import time
+from unittest.mock import patch
from crewai.utilities.rw_lock import RWLock
@@ -262,3 +263,49 @@ def test_manual_acquire_release():
with lock.r_locked():
pass
+
+
+def test_interrupted_read_acquire_does_not_drop_reader_count():
+ lock = RWLock()
+ lock.w_acquire()
+ try:
+ with patch.object(lock._cond, "wait", side_effect=KeyboardInterrupt):
+ with lock.r_locked():
+ raise AssertionError("read section entered without the lock")
+ except KeyboardInterrupt:
+ pass
+
+ assert lock._writer is True
+ assert lock._readers == 0
+ lock.w_release()
+
+ lock.r_acquire()
+ try:
+ assert lock._readers == 1
+ assert lock._writer is False
+ finally:
+ lock.r_release()
+ assert lock._readers == 0
+
+
+def test_interrupted_write_acquire_does_not_clear_writer():
+ lock = RWLock()
+ lock.w_acquire()
+ try:
+ with patch.object(lock._cond, "wait", side_effect=KeyboardInterrupt):
+ with lock.w_locked():
+ raise AssertionError("write section entered without the lock")
+ except KeyboardInterrupt:
+ pass
+
+ assert lock._writer is True
+ assert lock._readers == 0
+ lock.w_release()
+
+ lock.r_acquire()
+ try:
+ assert lock._readers == 1
+ assert lock._writer is False
+ finally:
+ lock.r_release()
+ assert lock._readers == 0