82 lines
1.3 KiB
Python
82 lines
1.3 KiB
Python
|
# Bryan Schumaker (8/7/2010)
|
||
|
|
||
|
events = dict()
|
||
|
from threading import Thread
|
||
|
|
||
|
|
||
|
class EventThread(Thread):
|
||
|
def __init__(self, func, action, arg):
|
||
|
Thread.__init__(self)
|
||
|
self.func = func
|
||
|
self.action = action
|
||
|
self.arg = arg
|
||
|
|
||
|
def run(self):
|
||
|
res = call("BGTHREAD", self.func, self.arg)
|
||
|
start("POST%s" % self.action, res)
|
||
|
|
||
|
|
||
|
def invite(key, func):
|
||
|
global events
|
||
|
if key not in events:
|
||
|
events[key] = set()
|
||
|
events[key].add(func)
|
||
|
|
||
|
|
||
|
def uninvite(key, func):
|
||
|
global events
|
||
|
if key not in events:
|
||
|
return
|
||
|
events[key].discard(func)
|
||
|
|
||
|
|
||
|
def start(key, arg=None):
|
||
|
global events
|
||
|
if key not in events:
|
||
|
return
|
||
|
for func in events[key]:
|
||
|
try:
|
||
|
if arg == None:
|
||
|
func()
|
||
|
else:
|
||
|
func(arg)
|
||
|
except Exception,e:
|
||
|
print
|
||
|
print "===== EVENT ERROR ====="
|
||
|
print "Event:", key
|
||
|
print "Function:", func
|
||
|
print "Args:", arg
|
||
|
print e
|
||
|
print "The function has been uninvited from this event"
|
||
|
print "====="
|
||
|
|
||
|
|
||
|
def start_thread(func, action, arg):
|
||
|
try:
|
||
|
th = EventThread(func, action, arg)
|
||
|
th.start()
|
||
|
return True
|
||
|
except Exception,e:
|
||
|
print e
|
||
|
return False
|
||
|
|
||
|
|
||
|
def call(action, func=None, arg=None, bg=False):
|
||
|
start("PRE%s" % action, arg)
|
||
|
if func == None:
|
||
|
return None
|
||
|
|
||
|
if bg == True:
|
||
|
res = start_thread(func, action, arg)
|
||
|
else:
|
||
|
if arg == None:
|
||
|
res = func()
|
||
|
else:
|
||
|
res = func(arg)
|
||
|
start("POST%s" % action, res)
|
||
|
return res
|
||
|
|
||
|
|
||
|
|
||
|
|