日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python如何獲取多線程返回結果_python

作者:vv安的淺唱 ? 更新時間: 2022-07-11 編程語言

Python獲取多線程返回結果

在 Python 的多線程中,有時候我們會需要每一個線程中返回的結果。

然而,在經過我的多番嘗試、以及網上各種博客顯示,在 Python3 中是無法獲得單個線程中返回的結果的,因此我們需要定義一個類來實現這個過程

這個類的定義如下:

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

然后我們就可以通過調用這個類里的函數,get_result() 來獲取每個線程中返回的結果了,以下是一個測試的實例,多線程調用一個相加的函數,經過實驗,是能夠獲取到所有線程返回的結果的。

import threading
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 add(num):
? ? result = num + 5
? ? return result
if __name__ == '__main__':
? ? data = []
? ? threads = []
? ? nums = [1, 2, 3]
? ? for num in nums:
? ? ? ? t = MyThread(add, args = (num, ))
? ? ? ? threads.append(t)
? ? ? ? t.start()
? ? for t in threads:
? ? ? ? t.join()
? ? ? ? data.append(t.get_result())
? ? print(data)

Python多線程實現

from threading import Thread
def func():
    for i in range(100):
        print('func',i)
if __name__ == '__main__':
    t=Thread(target=func)
    t.start()
    for i in range(100):
        print('main',i)

線程池:

  • 一次性開辟一些線程,我們用戶直接給線程池子提交任務,線程任務的調度交給線程池。
from concurrent.futures import ThreadPoolExecutor
def func(name):
    for i in range(20):
        print(name,i)
if __name__ == '__main__':
    #創建線程池
    with ThreadPoolExecutor(10) as t:
        for i in range(10):
            t.submit(func,name=f'線程{i}')
    print('over')#等待線程全部執行完畢,才會執行該行代碼

原文鏈接:https://blog.csdn.net/weixin_43354181/article/details/85933378

欄目分類
最近更新