python多線程中獲取函數(shù)返回值的三種方法
方法一:使用隊(duì)列
import queue
import threading
import sys
import time
q=queue.Queue()
def func1(x,y):
func_name = sys._getframe().f_code.co_name # 獲取函數(shù)名
print("%s run ....." % func_name)
q.put((x+y,func_name))
def func2(x,y):
func_name = sys._getframe().f_code.co_name
print("%s run ...." %func_name)
q.put((x-y,func_name))
if __name__ == "__main__":
result=[]
t1=threading.Thread(target=func1,name="thread1",args=(10,5))
t2=threading.Thread(target=func2,name="thread2",args=(20,1))
print('*'*20)
t1.start()
t2.start()
t1.join()
t2.join()
while not q.empty():# 隊(duì)列為空返回True,反之False
result.append(q.get())
for item in result:
if item[1] == func1.__name__:
print("%s return value is: %s" %(item[1],item[0]))
elif item[1] == func2.__name__:
print("%s return value is: %s" %(item[1],item[0]))
運(yùn)行結(jié)果:
********************
func1 run .....
func2 run ....
func1 return value is: 15
func2 return value is: 19
方法二: 封裝 threading.Thread,重寫 run 方法
class mythread(threading.Thread):
def __init__(self,func,args=()):
super(mythread, self).__init__()
self.func=func
self.args=args
def run(self):
self.result=self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
def foo(a,b,c):
time.sleep(1)
return a*2,b*2,c*2
li = []
for i in range(4):
t=mythread(foo,args=(i,i+1,i+2))
li.append(t)
t.start()
for t in li:
t.join()
print(t.get_result())
# 運(yùn)行結(jié)果
(0, 2, 4)
(2, 4, 6)
(4, 6, 8)
(6, 8, 10)方法三:使用進(jìn)程池
def func(msg):
print("msg:",msg)
time.sleep(3)
print("end")
return "done" + msg
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4)
result = []
for i in range(3):
msg = "hello %d" %i
result.append(pool.apply_async(func,(msg,)))
pool.close()
pool.join()
for res in result:
print(res)
print(":::",res.get())
# 運(yùn)行結(jié)果
msg: hello 0
msg: hello 1
msg: hello 2
end
end
end
<multiprocessing.pool.ApplyResult object at 0x0000027BF6B3F0D0>
::: donehello 0
<multiprocessing.pool.ApplyResult object at 0x0000027BF6F4FDF0>
::: donehello 1
<multiprocessing.pool.ApplyResult object at 0x0000027BF6F4FDC0>
::: donehello 2到此這篇關(guān)于python多線程中獲取函數(shù)返回值的三種方法的文章就介紹到這了,更多相關(guān)python多線程中獲取函數(shù)返回值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決python3 json數(shù)據(jù)包含中文的讀寫問題
這篇文章主要介紹了解決python3 json數(shù)據(jù)包含中文的讀寫問題,需要的朋友可以參考下2021-05-05
win10+anaconda安裝yolov5的方法及問題解決方案
這篇文章主要介紹了win10+anaconda安裝yolov5的方法及問題解決方案,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Python生成任意波形并存為txt的實(shí)現(xiàn)
本文主要介紹了Python生成任意波形并存為txt的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
Python快速轉(zhuǎn)換numpy數(shù)組中Nan和Inf的方法實(shí)例說明
今天小編就為大家分享一篇關(guān)于Python快速轉(zhuǎn)換numpy數(shù)組中Nan和Inf的方法實(shí)例說明,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02

