Python多執行緒獲取返回值

2021-09-18 07:19:38 字數 1023 閱讀 2939

在使用多執行緒的時候難免想要獲取其操作完的返回值進行其他操作,下面的方法以作參考:

一,首先重寫threading類,使其滿足呼叫特定的方法獲取其返回值 

import threading

class mythread(threading.thread):

"""重寫多執行緒,使其能夠返回值"""

def __init__(self, target=none, args=()):

super(mythread, self).__init__()

self.func = target

self.args = args

def run(self):

self.result = self.func(*self.args)

def get_result(self):

try:

return self.result # 如果子執行緒不使用join方法,此處可能會報沒有self.result的錯誤

except exception:

return none

二,呼叫get_result()方法,最終列表retval就是多執行緒返回值的集合:

def parse_detail_page(self,items_list):

retval, retlist, _threads = , ,

for url in items_list:

t = mythread(target=self.threaditem, args=(url,))

t.start()

for t in _threads:

t.join()

def threaditem(self,url):

"""多執行緒請求""" 

response = requests.get(url)

return response.text

posted @ 2019-04-15 16:09

編輯收藏

Python多執行緒獲取返回值

在使用多執行緒的時候難免想要獲取其操作完的返回值進行其他操作,下面的方法以作參考 一,首先重寫threading類,使其滿足呼叫特定的方法獲取其返回值 import threadingclass mythread threading.thread 重寫多執行緒,使其能夠返回值 def init se...

Python 獲取多執行緒獲取返回值

1.通過重寫thread類,自定義乙個get result 方法 重新定義帶返回值的執行緒類 from threading import thread from time import sleep,time class mythread thread def init self,func,args ...

獲取Python多執行緒的返回值

用python多執行緒時,遇到需要獲取每個執行緒返回值的問題,經查資料學習總結如下 python中使用執行緒有兩種方式 用方法包裝執行緒和用類包裝執行緒 方法 一 用方法包裝執行緒 thread start new thread function args kwargs function 表示執行緒...