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

    在我们实际编码中,会遇到一些并行的任务,因为单个任务无法最大限度的使用计算机资源。使用并行任务,可以提高代码效率,最大限度的发挥计算机的性能。python实现并行任务可以有多进程,多线程,协程等方式。

    进程,线程,协程

    • 进程

    进程是程序运行的基本单位,资源分配和独立运行的基本单位。

    多进程实现并行任务代码:

     import multiprocessing
     import time
    
     def test(interval):
         n = 5
         while n > 0:
             time.sleep(interval)
             n -= 1
    
    
     if __name__ == "__main__":
         p = multiprocessing.Process(target = test, args = (3,))
         p1 = multiprocessing.Process(target = test, args = (3,))
         p2 = multiprocessing.Process(target = test, args = (3,))
         p3 = multiprocessing.Process(target = test, args = (3,))
    
         p.start()
         p1.start()
         p2.start()
         p3.start()
         print("p.pid:", p.pid)
         print("p1.pid:", p.pid)
         print("p2.pid:", p.pid)
         print("p3.pid:", p.pid)
    

    执行结果

    • 线程

    通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程可以利用进程所拥有的资源,在引入线程的操作系统中,通常都是把进程作为分配资源的基本单位,而把线程作为独立运行和独立调度的基本单位,由于线程比进程更小,基本上不拥有系统资源,故对它的调度所付出的开销就会小得多,能更高效的提高系统多个程序间并发执行的程度。

    多线程实现并行(这里采用线程池):

    import threadpool
    import threading
    import time
    
    task_pool = threadpool.ThreadPool(10)
    
    def func(t):
        print(f'sleep {t} s. {threading.currentThread()}')
        time.sleep(t)
        print(f'{threading.currentThread()} have Done!!')
    
    args = [5 for i in range(5)]
    rs = threadpool.makeRequests(func, args)
    for req in rs:
        task_pool.putRequest(req)
    task_pool.wait()
    

    运行结果

    • 协程

    协程,又称微线程,是为非抢占式多任务产生子程序的计算机程序组件,协程允许不同入口点在不同位置暂停或开始执行程序。
    简单来讲,就是我们可以在执行的时候停下来执行另一子程序,当子程序执行完之后在此切换回来。并且是非阻塞的,也就意味着我们可以同时执行多个协程。
    也因为协程是单线程,所以我们切换所需要的开销最小,效率最高。

    实现代码:

    import asyncio
    import threading
    import random
    
    import time
    
    async def test(t, count):
        print(f'sleep {t} s. {threading.currentThread()}')
        # 使用asyncio.sleep() 而不用time.sleep() 是因为time.sleep()回挂起整个线程,
        # 而协程是基于单线程的,所以会block住
        #time.sleep(4)
        r = await asyncio.sleep(t)
        return t
    
    def main():
        print("start ..")
        start =  time.time()
        loop = asyncio.get_event_loop()
        tasks = [test(1, i)  for i in range(5)]
        loop.run_until_complete(asyncio.wait(tasks))
        loop.close()
        print(f'{time.time()-start}, finall {c}')
        return c
    
    if __name__ == '__main__':
        x = main()
    
    

    运行结果

  • 相关阅读:
    SqL读取XML、解析XML、SqL将XML转换DataTable、SqL将XML转换表
    C#DataTable复制、C#DataTable列复制、C#DataTable字段复制
    Dev、GridControl的模糊查询
    C#两个时间相减
    C# % 和 /
    C#时间、日期 的操作
    linux文件操作
    shell ftp上传下载文件
    POM详细配置
    maven 本地setting.xml配置
  • 原文地址:https://www.cnblogs.com/yuzhenjie/p/9737289.html
Copyright © 2011-2022 走看看