參考:python多線程執行同一個函數任務之threading、ThreadPoolExecutor.map
主要實現的是多個線程同時是完成一個大型任務,代碼的思路是把大任務分解,得到每個線程各自需要處理的任務量,然後再把任務函數和任務量分別放入不同線程中
如果要換成自己的任務的話,要改的地方:
_l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
換成你自己需要處理的總任務量- 在
split_count = 2
選擇每個線程的任務量 def work(df, _list)
換成自己的任務函數,此處return
的內容會存到results
中results = t.map(work, new_list, count_list)
的map
中第一位表示你的任務函數,後面兩個爲你的任務所需要傳入的變量- 最後再用多層
for
循環取出results
的結果
# -*- coding: utf-8 -*-
import math
import random
import time
from concurrent.futures import ThreadPoolExecutor
def split_list():
# 線程列表
new_list = []
count_list = []
# 需要處理的數據
_l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 每個線程處理的數據大小
split_count = 2
# 需要的線程個數
times = math.ceil(len(_l) / split_count)
count = 0
for item in range(times):
_list = _l[count: count + split_count]
new_list.append(_list)
count_list.append(count)
count += split_count
return new_list, count_list
def work(df, _list):
""" 線程執行的任務,讓程序隨機sleep幾秒
:param df:
:param _list:
:return:
"""
sleep_time = random.randint(1, 5)
print(f'count is {df},sleep {sleep_time},list is {_list}')
time.sleep(sleep_time)
return sleep_time, df, _list
def use():
new_list, count_list = split_list()
with ThreadPoolExecutor(max_workers=len(count_list)) as t:
results = t.map(work, new_list, count_list)
# 或執行如下兩行代碼
# pool = ThreadPoolExecutor(max_workers=5)
# 使用map的優點是 每次調用回調函數的結果不用手動的放入結果list中
# results = pool.map(work, new_list, count_list)
# map返回一個迭代器,其中的回調函數的參數 最好是可以迭代的數據類型,如list;如果有 多個參數 則 多個參數的 數據長度相同;
# 如: pool.map(work,[[1,2],[3,4]],[0,1]]) 中 [1,2]對應0 ;[3,4]對應1 ;其實內部執行的函數爲 work([1,2],0) ; work([3,4],1)
# map返回的結果 是 有序結果;是根據迭代函數執行順序返回的結果
print(type(results))
# 如下2行 會等待線程任務執行結束後 再執行其他代碼
for ret in results:
print(ret)
print('thread execute end!')
if __name__ == '__main__':
use()