Skip to content

Commit 7aded6f

Browse files
authored
feat(fifolock): acquire and release Logic optimization (#1251)
Signed-off-by: CLFutureX <chenyongqyl@163.com>
1 parent c4cf745 commit 7aded6f

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

openhands-sdk/openhands/sdk/conversation/fifo_lock.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
5050
Returns:
5151
True if lock was acquired, False otherwise.
5252
"""
53-
me = threading.Condition(self._mutex)
5453
ident = threading.get_ident()
5554
start = time.monotonic()
5655

@@ -60,21 +59,27 @@ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
6059
self._count += 1
6160
return True
6261

62+
if self._owner is None and not self._waiters:
63+
self._owner = ident
64+
self._count = 1
65+
return True
66+
67+
if not blocking:
68+
# Give up immediately
69+
return False
70+
6371
# Add to wait queue
72+
me = threading.Condition(self._mutex)
6473
self._waiters.append(me)
6574

6675
while True:
6776
# If I'm at the front of the queue and nobody owns it → acquire
6877
if self._waiters[0] is me and self._owner is None:
78+
self._waiters.popleft()
6979
self._owner = ident
7080
self._count = 1
7181
return True
7282

73-
if not blocking:
74-
# Give up immediately
75-
self._waiters.remove(me)
76-
return False
77-
7883
if timeout >= 0:
7984
remaining = timeout - (time.monotonic() - start)
8085
if remaining <= 0:
@@ -95,11 +100,12 @@ def release(self) -> None:
95100
with self._mutex:
96101
if self._owner != ident:
97102
raise RuntimeError("Cannot release lock not owned by current thread")
98-
103+
assert self._count >= 1, (
104+
"When releasing the resource, the count must be >= 1"
105+
)
99106
self._count -= 1
100107
if self._count == 0:
101108
self._owner = None
102-
self._waiters.popleft()
103109
if self._waiters:
104110
self._waiters[0].notify()
105111

0 commit comments

Comments
 (0)