Skip to content

Commit c40c161

Browse files
alonks1234Alon Kosowsky-Sachs
and
Alon Kosowsky-Sachs
authored
fix: prevent multiple tasks from using the same connection (#5)
Co-authored-by: Alon Kosowsky-Sachs <[email protected]>
1 parent 313053f commit c40c161

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

tcp_modbus_aio/client.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,8 @@ async def send_modbus_message(
446446
raise ModbusConcurrencyError(
447447
f"Failed to acquire lock to send request {msg_str} to modbus device {self.host}"
448448
)
449+
450+
i_have_lock = True
449451
time_budget_remaining -= lock_t()
450452

451453
try:
@@ -528,6 +530,7 @@ async def send_modbus_message(
528530

529531
# release the lock before retrying (so we can re-get it)
530532
self._comms_lock.release()
533+
i_have_lock = False # Don't release someone elses lock in the finally
531534

532535
return await self.send_modbus_message(
533536
request_function,
@@ -539,7 +542,7 @@ async def send_modbus_message(
539542
f"Request {msg_str} failed to {self.host}:{self.port} ({type(e).__name__}({e}))"
540543
) from e
541544
finally:
542-
if self._comms_lock.locked():
545+
if self._comms_lock.locked() and i_have_lock:
543546
self._comms_lock.release()
544547

545548
self._consecutive_timeouts = 0

0 commit comments

Comments
 (0)