Skip to content

Commit

Permalink
fix: fix race condition in timer
Browse files Browse the repository at this point in the history
When scheduling a new task using the Timer class,
the lock protecting the timer object is taken optimistically,
which can cause a race condition
where the new timer thread does not start its successor.
  • Loading branch information
andrzej-stencel committed Dec 23, 2021
1 parent 5d0d54d commit 6b23c0c
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions sumologic_collectd_metrics/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,20 @@ def start_timer(self):
Start a thread to periodically run task func
"""

if hasattr(self, 'collectd'):
self.collectd.debug('Timer has been run: %s.' %
self.__class__.__name__)
if self.run_count >= self.run_count_reset:
with self.start_timer_lock:
if hasattr(self, 'collectd'):
self.collectd.info('Timer %s has run %s times.' % (
self.__class__.__name__, self.run_count))
self.run_count = 0
self.run_count += 1

self.timer = threading.Timer(self.interval, self.start_timer)
self.timer.daemon = True
# Lock to resolve racing condition for start_timer and reset_timer
if self.start_timer_lock.acquire(False): # pylint: disable=R1732
if not self.timer.is_alive():
self.timer.start()
self.start_timer_lock.release()
self.collectd.debug('Timer has been run: %s.' %
self.__class__.__name__)
if self.run_count >= self.run_count_reset:
if hasattr(self, 'collectd'):
self.collectd.info('Timer %s has run %s times.' % (
self.__class__.__name__, self.run_count))
self.run_count = 0
self.run_count += 1

self.timer = threading.Timer(self.interval, self.start_timer)
self.timer.daemon = True
self.timer.start()

self.task()

Expand Down

0 comments on commit 6b23c0c

Please sign in to comment.