新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:如何使用python多線程并返回值?
有小伙伴在后臺給小編留言,希望出這一起關(guān)于多線程返回值的問題,于是,小編整理了很多內(nèi)容,最終給大家呈現(xiàn)多種方式,希望大家可以在不同的場景應(yīng)用時,能有不同的效果,一起來看下吧~

Python 從多線程中返回值,有多種方法:
1、常見的有寫一個自己的多線程類,寫一個方法返回。
2、可以設(shè)置一個全局的隊列返回值。
3、也可以用multiprocessing.pool.ThreadPool 。
下面寫一個類從線程中返回值
# coding:utf-8 import time from threading import Thread def foo(number): time.sleep(20) return number class MyThread(Thread): def __init__(self, number): Thread.__init__(self) self.number = number def run(self): self.result = foo(self.number) def get_result(self): return self.result thd1 = MyThread(3) thd2 = MyThread(5) thd1.start() thd2.start() thd1.join() thd2.join() print thd1.get_result() print thd2.get_result()
另外,自帶的Thread 實例并沒有返回結(jié)果的方法. 需要自己實現(xiàn),自己定義一個類:
class CustomTask: def __init__(self): self._result = None def run(self, *args, **kwargs): # 你的代碼, 你用來進行多線程 result = ... self._result = result def get_result(self): return self._result 這里自己實現(xiàn)了 `get_result` 方法。 使用 import threading ct = CustomTask() t = threading.Thread(target=ct.run, args=(...)) t.start() # 結(jié)束之后 result = ct.get_result()
大家可以根據(jù)以上內(nèi)容,了解自己的需求,在適合的場景里去使用以上,相信大家的python進程更充實哦~如果還想知道更多的python知識,可以到python學(xué)習(xí)網(wǎng)進行查詢。
網(wǎng)頁名稱:創(chuàng)新互聯(lián)Python教程:如何使用python多線程并返回值?
網(wǎng)頁URL:http://m.fisionsoft.com.cn/article/dhiccgi.html


咨詢
建站咨詢
