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       
    
    
    不论你在什么时候开始,重要的是开始之后就不要停止。 不论你在什么时候结束,重要的是结束之后就不要悔恨。
  • 相关阅读:
    React Native配置和使用
    使用ES6语法重构React代码
    git 起点
    Win32API程序中自建按钮
    C语言中数组与指针
    我的第一个博客
    Solr6.5配置中文分词IKAnalyzer和拼音分词pinyinAnalyzer (二)
    Solr6.5在Centos6上的安装与配置 (一)
    PHP版微信公共平台消息主动推送,突破订阅号一天只能发送一条信息限制
    MariaDB+Keepalived双主高可用配置MySQL-HA
  • 原文地址:https://www.cnblogs.com/yunhgu/p/14794444.html
Copyright © 2011-2022 走看看