在学习threadpool
怎么使用多个线程 打印 1到100呢
def thread_job2(**kwargs):
sleep(0.5)
print('thread_name{1} is print is {0} \n'.format(kwargs['a'], threading.Thread.name))
print(threading.enumerate(), '\n')
def thread_print():
pool = threadpool.ThreadPool(4)
request = threadpool.makeRequests(thread_job2, [(None, {'a': number}) for number in range(1, 101)])
for req in request:
pool.putRequest(req)
pool.wait()
if __name__ == '__main__':
thread_print()
我用的是命名参数
时间戳 2021年3月29日
上面的pool 貌似太老了,现在使用 ThreadPoolExecutor
# -*- coding: utf-8 -*-
# create time : 2021-03-29 14:33
# author : CY
# file : thread_pool.py
# modify time:
import random
import threading
from concurrent.futures import ThreadPoolExecutor
from time import sleep
from concurrent.futures._base import ALL_COMPLETED, wait
from Page.web.method.random_data import list_of_groups
def thread_job2(**kwargs):
sleep(random.randint(1, 2))
for i in kwargs['num_list']:
print(i)
data = {
'thread_name': threading.Thread.name,
'num_list': kwargs['num_list']
}
return data
def thread_print():
# 这个list 是 1~100
num_list = range(1, 101)
print(num_list)
# 定义线程最大个数
max_workers = 4
# 分配job 执行 的 参数
new_num_list = list_of_groups(init_list=num_list, children_list_len=10)
# 上面的结果是 [
# [1~10],
# [11~20],
# [21~30],
# 等
# ]
# 创建一个包含4条线程的线程池
pool = ThreadPoolExecutor(max_workers=max_workers)
# 向线程池提交任务
all_task = [pool.submit(thread_job2, **{'num_list': task_num_list}) for task_num_list in new_num_list]
# 全部执行完 在返回结果
wait(all_task, return_when=ALL_COMPLETED)
for one_thread in all_task:
result = one_thread.result()
print(result)
print(result['num_list'])
if __name__ == '__main__':
thread_print()
job 传参 dict 就 加个 **