安装:

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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐