python线程池库threadpool使用实例

本文介绍了如何安装Python的threadpool库,并通过一个实际示例展示了其使用方法,帮助理解线程池在并发处理任务中的应用。

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

安装:

pip install threadpool


使用实例:

# -*- coding: utf-8 -*-

import threadpool


def hello(a):
    return 'hello: %s' % a


def world(a, b):
    return 'world: %s, %s' % (a, b)


def foobar(a, b, c):
    return 'foobar: %s, %s, %s' % (a, b, c)


def print_result(req, result):
    print('The result is %s %s' % (req.requestID, result))


data1 = [1, 2, 3, 4, 5]

lst1 = (6, 6)
lst2 = (7, 7)
lst3 = (8, 8)
data2 = [(lst1, None), (lst2, None), (lst3, None)]

dct1 = {'a': 8, 'b': 9, 'c': 10}
dct2 = {'a': 11, 'b': 12, 'c': 13}
data3 = [(None, dct1), (None, dct2)]

pool = threadpool.ThreadPool(5)
requests1 = threadpool.makeRequests(hello, data1, print_result)
requests2 = threadpool.makeRequests(world, data2, print_result)
requests3 = threadpool.makeRequests(foobar, data3, print_result)

[pool.putRequest(req) for req in requests1]
[pool.putRequest(req) for req in requests2]
[pool.putRequest(req) for req in requests3]

pool.wait()

输出结果:

The result is 39748664 hello: 1
The result is 39748720 hello: 2
The result is 39748776 hello: 3
The result is 39748832 hello: 4
The result is 39748888 hello: 5
The result is 39748944 world: 6, 6
The result is 39749000 world: 7, 7
The result is 39749056 world: 8, 8
The result is 39749112 foobar: 8, 9, 10
The result is 39749168 foobar: 11, 12, 13

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值