threadpool 与 ThreadPoolExecutor 输出1~100

本文详细介绍了如何使用Python的ThreadPoolExecutor来并行处理任务,通过将1至100的数字列表分割成多个子列表,并将这些子列表作为参数传递给线程池中的工作线程,实现多线程并行打印数字,从而提高程序执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在学习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 就 加个 **

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值