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

Python 從多線程中返回值,有多種方法:
1、常見的有寫一個(gè)自己的多線程類,寫一個(gè)方法返回。
2、可以設(shè)置一個(gè)全局的隊(duì)列返回值。
3、也可以用multiprocessing.pool.ThreadPool 。
下面寫一個(gè)類從線程中返回值
# 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 實(shí)例并沒有返回結(jié)果的方法. 需要自己實(shí)現(xiàn),自己定義一個(gè)類:
class CustomTask: def __init__(self): self._result = None def run(self, *args, **kwargs): # 你的代碼, 你用來進(jìn)行多線程 result = ... self._result = result def get_result(self): return self._result 這里自己實(shí)現(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)容,了解自己的需求,在適合的場(chǎng)景里去使用以上,相信大家的python進(jìn)程更充實(shí)哦~如果還想知道更多的python知識(shí),可以到python學(xué)習(xí)網(wǎng)進(jìn)行查詢。
網(wǎng)頁(yè)標(biāo)題:創(chuàng)新互聯(lián)Python教程:如何使用python多線程并返回值?
當(dāng)前地址:http://m.5511xx.com/article/dhiccgi.html


咨詢
建站咨詢
