Add threading utilities

This commit is contained in:
moyamo 2016-01-07 17:56:55 +02:00
parent 9c32dfbb38
commit e850402095
2 changed files with 28 additions and 1 deletions

19
threadutils.py Normal file
View file

@ -0,0 +1,19 @@
import Queue
import threading
# This queue is for other threads that want to execute code in the main thread
eventQueue = Queue.Queue()
def runInThread(threadFunc, callback):
"""
Executes threadFunc in a new thread. The result of threadFunc will be
pass as the first argument to callback. callback will be called in the main
thread.
"""
def helper():
# Execute threadfunc in new thread
result = threadFunc()
# Queue callback to be call in main thread
eventQueue.put(lambda: callback(result))
thread = threading.Thread(target=helper)
thread.start()

View file

@ -29,8 +29,8 @@ import logging
import asyncore import asyncore
import sys, os import sys, os
import e4u import e4u
import threading
import Queue import Queue
import threadutils
sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.getcwd())
@ -89,6 +89,7 @@ plugin.handleBackendConfig({
], ],
}) })
while True: while True:
try: try:
asyncore.loop(timeout=1.0, count=10, use_poll = True) asyncore.loop(timeout=1.0, count=10, use_poll = True)
@ -101,6 +102,13 @@ while True:
break break
if closed: if closed:
break break
while True:
try:
callback = threadutils.eventQueue.get_nowait()
except Queue.Empty:
break
else:
callback()
except SystemExit: except SystemExit:
break break
except: except: