Skip to content

Commit c495735

Browse files
committed
fix(sessions): clean up threading on kill+flush
This follows the precedent set in transport.flush, and helps me with my project to assert thread hygeine in sentry test suite (related: DI-1008), but also makes the system much more deterministic for everyone. This will cause shutdown to be quite slow until #4561 goes in. So I'd reject this if you reject that.
1 parent 5709b25 commit c495735

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

sentry_sdk/sessions.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,9 @@ def __init__(
165165

166166
def flush(self):
167167
# type: (...) -> None
168-
pending_sessions = self.pending_sessions
169-
self.pending_sessions = []
168+
with self._thread_lock:
169+
pending_sessions = self.pending_sessions
170+
self.pending_sessions = []
170171

171172
with self._aggregate_lock:
172173
pending_aggregates = self.pending_aggregates
@@ -190,6 +191,26 @@ def flush(self):
190191
if len(envelope.items) > 0:
191192
self.capture_func(envelope)
192193

194+
# hygiene: deterministically clean up any stopping thread
195+
if not self._thread_stopping():
196+
return
197+
with self._thread_lock:
198+
if not self._thread_stopping():
199+
return
200+
if self._thread: # typing
201+
self._thread.join()
202+
self._thread = None
203+
self._thread_for_pid = None
204+
205+
def _thread_stopping(self):
206+
# type: (...) -> bool
207+
return (
208+
not self._running
209+
and self._thread is not None
210+
# we are the parent thread:
211+
and self._thread_for_pid == os.getpid()
212+
)
213+
193214
def _ensure_running(self):
194215
# type: (...) -> None
195216
"""

0 commit comments

Comments
 (0)