Skip to content

Fix coordinator lock contention during close() #2652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 18 additions & 17 deletions kafka/coordinator/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -857,14 +857,12 @@ def _disable_heartbeat_thread(self):
self._heartbeat_thread.disable()

def _close_heartbeat_thread(self, timeout_ms=None):
with self._lock:
if self._heartbeat_thread is not None:
heartbeat_log.info('Stopping heartbeat thread')
try:
self._heartbeat_thread.close(timeout_ms=timeout_ms)
except ReferenceError:
pass
self._heartbeat_thread = None
if self._heartbeat_thread is not None:
try:
self._heartbeat_thread.close(timeout_ms=timeout_ms)
except ReferenceError:
pass
self._heartbeat_thread = None

def __del__(self):
try:
Expand Down Expand Up @@ -1047,17 +1045,20 @@ def disable(self):
self.enabled = False

def close(self, timeout_ms=None):
if self.closed:
return
self.closed = True
with self.coordinator._lock:
if self.closed:
return

# Generally this should not happen - close() is triggered
# by the coordinator. But in some cases GC may close the coordinator
# from within the heartbeat thread.
if threading.current_thread() == self:
return
heartbeat_log.info('Stopping heartbeat thread')
self.closed = True

with self.coordinator._lock:
# Generally this should not happen - close() is triggered
# by the coordinator. But in some cases GC may close the coordinator
# from within the heartbeat thread.
if threading.current_thread() == self:
return

# Notify coordinator lock to wake thread from sleep/lock.wait
self.coordinator._lock.notify()

if self.is_alive():
Expand Down
Loading