Skip to content
Draft
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
30 changes: 27 additions & 3 deletions src/watchdog/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ def __init__(self) -> None:
self.daemon = True
else:
self.setDaemon(True)
# Provides synchronization for start() and stop(). They can be
# called multiple times, out-of-order or concurrently. We want to do
# something predicable in all cases.
self._thread_life_lock = threading.Lock()
self._started_event: threading.Event | None = None
self._stopped_event = threading.Event()

@property
Expand All @@ -60,7 +65,16 @@ def on_thread_stop(self) -> None:

def stop(self) -> None:
"""Signals the thread to stop."""
self._stopped_event.set()
with self._thread_life_lock:
if self._stopped_event.is_set():
return # already stopped
started_event = self._started_event
if started_event is not None:
started_event.wait() # not finished start, wait
with self._thread_life_lock:
if self._stopped_event.is_set():
return # we raced with another stop, done
self._stopped_event.set()
self.on_thread_stop()

def on_thread_start(self) -> None:
Expand All @@ -72,8 +86,18 @@ def on_thread_start(self) -> None:
"""

def start(self) -> None:
self.on_thread_start()
threading.Thread.start(self)
with self._thread_life_lock:
if self._stopped_event.is_set():
return # stop() was called, so don't start
self._started_event = threading.Event()
try:
self.on_thread_start()
threading.Thread.start(self)
finally:
with self._thread_life_lock:
# indicate to stop() methods waiting that start is done
self._started_event.set()
self._started_event = None


def load_module(module_name: str) -> ModuleType:
Expand Down
Loading