From e85040209538bf6669e807c6f424c40b146208ed Mon Sep 17 00:00:00 2001 From: moyamo Date: Thu, 7 Jan 2016 17:56:55 +0200 Subject: [PATCH] Add threading utilities --- threadutils.py | 19 +++++++++++++++++++ transwhat.py | 10 +++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 threadutils.py diff --git a/threadutils.py b/threadutils.py new file mode 100644 index 0000000..59e7d51 --- /dev/null +++ b/threadutils.py @@ -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() diff --git a/transwhat.py b/transwhat.py index 776b1cc..07e36bf 100755 --- a/transwhat.py +++ b/transwhat.py @@ -29,8 +29,8 @@ import logging import asyncore import sys, os import e4u -import threading import Queue +import threadutils sys.path.insert(0, os.getcwd()) @@ -89,6 +89,7 @@ plugin.handleBackendConfig({ ], }) + while True: try: asyncore.loop(timeout=1.0, count=10, use_poll = True) @@ -101,6 +102,13 @@ while True: break if closed: break + while True: + try: + callback = threadutils.eventQueue.get_nowait() + except Queue.Empty: + break + else: + callback() except SystemExit: break except: