Skip to content

Commit ee62cc0

Browse files
committed
✨ TimeEvent is now thread safe.
1 parent 62a08c6 commit ee62cc0

2 files changed

Lines changed: 13 additions & 8 deletions

File tree

computer_vision_design_patterns/event.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: utf-8 -*-
2+
import threading
23
import time
34
from abc import ABC
45

@@ -29,20 +30,24 @@ def __init__(self, event_seconds_duration: float):
2930
super().__init__()
3031
self._event_seconds_duration = event_seconds_duration
3132
self._last_call_time = None
33+
self._lock = threading.Lock()
3234

3335
def trigger(self):
34-
self._last_call_time = time.time()
35-
self.activate()
36+
with self._lock:
37+
self._last_call_time = time.time()
38+
self.activate()
3639

3740
def _update_timer(self):
38-
if self._last_call_time is not None:
39-
if time.time() - self._last_call_time > self._event_seconds_duration:
40-
self.deactivate()
41-
self._last_call_time = None
41+
with self._lock:
42+
if self._last_call_time is not None:
43+
if time.time() - self._last_call_time > self._event_seconds_duration:
44+
self.deactivate()
45+
self._last_call_time = None
4246

4347
def is_active(self) -> bool:
4448
self._update_timer()
45-
return self.state == self.active.name
49+
with self._lock:
50+
return self.state == self.active.name
4651

4752

4853
class CountdownEvent(Event):
Lines changed: 1 addition & 1 deletion
Loading

0 commit comments

Comments
 (0)