zoukankan      html  css  js  c++  java
  • python之进程,线程,协程

    进程+线程

    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    """
    @author: yunhgu
    @time:   2021/5/21 14:55
    @file:   Process_async.py
    @description:
    """
    import time
    import asyncio
    import os
    import psutil
    import threading
    from concurrent.futures import ProcessPoolExecutor
    
    
    async def a():
        pid = os.getpid()
        ps = psutil.Process(pid)
        print(f"进程id:{pid} 线程数:{ps.num_threads()} 线程id:{threading.current_thread().ident}")
        await asyncio.sleep(1)
    
    
    async def b():
        await a()
    
    
    def run():
        loop = asyncio.get_event_loop()
        task = [b() for j in range(2)]
        loop.run_until_complete(asyncio.wait(task))
        loop.close()
    
    
    if __name__ == '__main__':
        start_time = time.time()
        p = ProcessPoolExecutor(4)
        for i in range(2):
            p.submit(run)
        p.shutdown(wait=True)
        print(f"耗费时间:{time.time() - start_time}")
    
    
    进程id:39100 线程数:5 线程id:39924
    进程id:39100 线程数:5 线程id:39924
    进程id:39216 线程数:5 线程id:31592
    进程id:39216 线程数:5 线程id:31592
    耗费时间:2.4648985862731934
    

    进程+线程

    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    """
    @author: yunhgu
    @time:   2021/5/21 15:23
    @file:   Process_thread.py
    @description:
    """
    import time
    import os
    import psutil
    import threading
    from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
    
    
    def a():
        pid = os.getpid()
        ps = psutil.Process(pid)
        print(f"进程id:{pid} 线程数:{ps.num_threads()} 线程id:{threading.current_thread().ident}")
        time.sleep(1)
    
    
    def run():
        t = ThreadPoolExecutor()
        for j in range(2):
            t.submit(a)
        t.shutdown(wait=True)
    
    
    if __name__ == '__main__':
        start_time = time.time()
        p = ProcessPoolExecutor(4)
        for i in range(2):
            p.submit(run)
        p.shutdown(wait=True)
        print(f"耗费时间:{time.time() - start_time}")
    
    
    进程id:35440 线程数:5 线程id:38792
    进程id:35440 线程数:6 线程id:31916
    进程id:34316 线程数:5 线程id:37796
    进程id:34316 线程数:6 线程id:38384
    耗费时间:2.2368392944335938       
    
    
    不论你在什么时候开始,重要的是开始之后就不要停止。 不论你在什么时候结束,重要的是结束之后就不要悔恨。
  • 相关阅读:
    Kubernetes 集成研发笔记
    Rust 1.44.0 发布
    Rust 1.43.0 发布
    PAT 甲级 1108 Finding Average (20分)
    PAT 甲级 1107 Social Clusters (30分)(并查集)
    PAT 甲级 1106 Lowest Price in Supply Chain (25分) (bfs)
    PAT 甲级 1105 Spiral Matrix (25分)(螺旋矩阵,简单模拟)
    PAT 甲级 1104 Sum of Number Segments (20分)(有坑,int *int 可能会溢出)
    java 多线程 26 : 线程池
    OpenCV_Python —— (4)形态学操作
  • 原文地址:https://www.cnblogs.com/yunhgu/p/14794444.html
Copyright © 2011-2022 走看看