2行代码实现python多线程

    python内置了一个concurrent.futures库,实现了对thread库的封装,使用非常简单,你只需要:

1.将需要多线程的程序封装为接受一个参数的函数;
2.将此函数传递给ThreadPoolExecutor类的map方法。

示例代码:

from concurrent.futures import ThreadPoolExecutor
from time import sleep
from random import randint


def a(n):
    print(n, 'start')
    s = randint(1, 10)  # 随机休眠s秒,模拟IO延迟
    sleep(s)
    print(n, s, 'finish')


print('test start')
with ThreadPoolExecutor(max_workers=100) as workers:  # 开100线程
    workers.map(a, range(20))
print('end')
运行结果:

test start
0 start
1 start
2 start
3 start
4 start
5 start
6 start
7 start
8 start
9 start
10 start
11 start
12 start
13 start
14 start
15 start
16 start
17 start
18 start
19 start
13 2 finish
14 3 finish
2 4 finish
12 4 finish
3 5 finish
16 5 finish
1 6 finish
10 6 finish
18 6 finish
5 7 finish
7 7 finish
6 8 finish
11 8 finish
15 8 finish
19 8 finish
0 9 finish
4 9 finish
9 9 finish
8 9 finish
17 10 finish
end



你可能感兴趣的:(2行代码实现python多线程)