我有一个关于python多线程的问题。基本上在我的软件里,我有一个功能,运行起来很昂贵。所以,我把它放在子线程中运行。但是,在函数运行期间,它将调用一个函数并更改对象的某些值,这将触发GUI更改。因此,我需要把它放回主线程。在
问题是我需要等待这个函数在主线程中完全完成,然后在子线程中继续这个函数。在
所以,我需要一个聪明的方法将作业发送回主线程并等待它完成。有人能给我一些建议吗?在
非常感谢。我在下面添加了我的运行线程方法
谨致问候import Queue
import logging
import sys
import time
import threading
DISABLE_THREADING = False
queue = Queue.Queue()
def run_in_sub_thread_named(name, function, *params):
if DISABLE_THREADING:
return function(*params)
th = _DEThread(function, *params)
task_info = TaskInfo(name)
th.task_info = task_info
running_tasks[th] = task_info
th.start()
return th
def run_in_main_thread(function, *params, **kwargs):
cur_thread = threading.currentThread()
cur_thread_name = cur_thread.getName()
in_main_thread = (cur_thread_name == 'MainThread')
if in_main_thread:
function(*params, **kwargs)
else:
queue.put((function, params, kwargs))
class _DEThread:
def __init__(self, function, *params):
self.thread = threading.Thread(target=self.execute)
self.thread.setDaemon(True)
self.function = function
self.params = params
self.name = ''
def start(self):
self.thread.start()
def execute(self):
try:
if self.params is ():
res = self.function()
else:
res = self.function(*self.params)
except:
run_in_main_thread(self._update_task_info,
'Exception: %s' % repr(sys.exc_info()))
raise
run_in_main_thread(self._update_task_info, res)
def _update_task_info(self, res):
if self in running_tasks:
task_info = running_tasks[self]
task_info.end_time = time.time()
task_info.result = res
finished_tasks[self] = task_info
del running_tasks[self]