Python线程池的创建与使用

线程池–concurrent

在这里插入图片描述
在这里插入图片描述

实战

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     : 2021/8/28 15:54
# @Author   : InsaneLoafer
# @File     : thread_pool.py

import os
import time
import threading
from concurrent.futures import ThreadPoolExecutor


lock = threading.Lock()  # 定义全局锁

def work(i):
    # lock.acquire()
    print(i, os.getpid())
    time.sleep(1)
    # lock.release()
    return 'result: %s' % i


if __name__ == '__main__':
    print(os.getpid())
    t = ThreadPoolExecutor(2)
    result = []
    for i in range(20):
        t_result = t.submit(work, (i,))
        result.append(t_result)

    for res in result:
        print(res.result())
34320
(0,) 34320
(1,) 34320
(2,)(3,)result: 0 
34320 
result: 134320

(4,)(5,)result: 2 
34320result: 3

 34320
(6,) 34320
(7,) 34320result: 4
result: 5

(8,)(9,)  result: 634320

34320result: 7

(10,)(11,)  34320result: 834320


result: 9
(12,)(13,)result: 10  34320
34320
result: 11

(14,)(15,)result: 12 
34320result: 13 

34320
(16,)(17,) result: 14 
34320result: 1534320


(18,)(19,)result: 16  34320

result: 17
34320
result: 18
result: 19

Process finished with exit code 0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值