[求助] Python 多线程通信 (好心人救救孩子,点开工资超级加倍)
如何从一个需要执行很久的线程当中获取返回数据
有一个线程当中的函数做 funcA,funcA 需要花费很多时间,并且 funcA 会返回我们需要的数据 我该如何获得其中的数据? 网上一般是
- 使用 queue 作为全局变量,但是如果在 funcA 里面 put 数据的话,在主线程当中 get 数据会返回 None,因为 funcA 会花费很多的时间,所以主线程获得的都是 None 。
q = queue.Queue(10) def funcA(): # 花费很多时间做一些事得到一个数组叫做 res for i in res: q.put(i) res=[] while not empty(q.get()): res.append(q.get())
- 是重构 thread 模块写一个自己的 thread 类,其中新建一个 get_result 方法。如果重构的话会发现也是 None,因为在 funcA 会使用很多的时间,然后使用 get_result 方法的话会返回 None,因为在 run 方法当中并没有返回数据。
class MyThread(Thread): def __init__(self, target, args): super(MyThread, self).__init__() self.func = target self.args = args def run(self): print("I have done") self.result = self.func(*self.args) def get_result(self): while self.lock: pass return self.result ............. ............. thread = MyThread(target=funca, args=(domain,)) thread.start() res=thread.get_result()
我也想过方法,比如在 get_result 当中等待 run 方法执行完毕,但是这样就会导致线程阻塞的问题
所以问题是如何在需要花费很多时间的线程当中得到数据并且不会阻塞。 跪求大神!!!