首页 > 编程语言 > 详细

python concurrent 的使用测试

时间:2021-07-13 15:16:34      阅读:14      评论:0      收藏:0      [点我收藏+]

说明

Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threading和multiprocessing的进一步抽象,对编写线程池/进程池提供了直接的支持.

代码测试

#! /usr/bin/env python
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# Name:         demo3
# Author:       yunhgu
# Date:         2021/7/8 15:17
# Description: 
# -------------------------------------------------------------------------------
import os
import time
import threading
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed


def work(x):
    time.sleep(1)
    temp = f"父进程{os.getppid()}:子进程{os.getpid()}:线程{threading.get_ident()}:{x}"
    return temp


def sub_thread():
    temp_list = []
    with ThreadPoolExecutor(max_workers=3) as t:
        task_list = [t.submit(work, i) for i in range(5)]
        for task in as_completed(task_list):
            if task.done():
                temp_list.append(task.result())
    return temp_list


def main():
    print(f"主进程:{os.getpid()}")
    path_list = []
    with ProcessPoolExecutor(max_workers=3) as p:
        task_list = [p.submit(sub_thread) for i in range(5)]
        for task in as_completed(task_list):
            if task.done():
                path_list.append(task.result())
    for path in path_list:
        print(path)


if __name__ == ‘__main__‘:
    main()

技术分享图片

python concurrent 的使用测试

原文:https://www.cnblogs.com/yunhgu/p/15005535.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!