use mutex to lock scheduler

This commit is contained in:
Romain Bignon 2010-07-14 17:11:19 +02:00
commit ba8d0921bb

View file

@ -17,7 +17,7 @@
import logging import logging
from threading import Timer, Event from threading import Timer, Event, RLock
__all__ = ['Scheduler'] __all__ = ['Scheduler']
@ -38,6 +38,7 @@ class IScheduler(object):
class Scheduler(IScheduler): class Scheduler(IScheduler):
def __init__(self): def __init__(self):
self.mutex = RLock()
self.stop_event = Event() self.stop_event = Event()
self.count = 0 self.count = 0
self.queue = {} self.queue = {}
@ -46,6 +47,7 @@ class Scheduler(IScheduler):
if self.stop_event.isSet(): if self.stop_event.isSet():
return return
with self.mutex:
self.count += 1 self.count += 1
logging.debug('function "%s" will be called in %s seconds' % (function.__name__, interval)) logging.debug('function "%s" will be called in %s seconds' % (function.__name__, interval))
timer = Timer(interval, self._callback, (self.count, function, args)) timer = Timer(interval, self._callback, (self.count, function, args))
@ -54,6 +56,7 @@ class Scheduler(IScheduler):
return self.count return self.count
def _callback(self, count, function, args): def _callback(self, count, function, args):
with self.mutex:
self.queue.pop(count) self.queue.pop(count)
return function(*args) return function(*args)
@ -65,6 +68,7 @@ class Scheduler(IScheduler):
def _wait_to_stop(self): def _wait_to_stop(self):
self.want_stop() self.want_stop()
with self.mutex:
for e in self.queue.itervalues(): for e in self.queue.itervalues():
e.cancel() e.cancel()
e.join() e.join()