python线程池库threadpool使用实例

来源:互联网 发布:感情 知乎 编辑:程序博客网 时间:2024/06/08 06:12

安装:

pip install threadpool


使用实例:

# -*- coding: utf-8 -*-import threadpooldef hello(a):    return 'hello: %s' % adef 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: 1The result is 39748720 hello: 2The result is 39748776 hello: 3The result is 39748832 hello: 4The result is 39748888 hello: 5The result is 39748944 world: 6, 6The result is 39749000 world: 7, 7The result is 39749056 world: 8, 8The result is 39749112 foobar: 8, 9, 10The result is 39749168 foobar: 11, 12, 13

0 0
原创粉丝点击