提高Python程序并发性的两种方式

发布时间:2023-05-12

利用多线程提高程序并发性

  1. 使用threading模块创建线程
    import threading
    def func():
        print("hello, world!")
    thread = threading.Thread(target=func)
    thread.start()
    
  2. 保证线程安全 对共享资源进行加锁
    import threading
    class SharedCounter:
        def __init__(self, val=0):
            self.val = val
            self.lock = threading.Lock()
        def increment(self):
            with self.lock:
                self.val += 1
        def decrement(self):
            with self.lock:
                self.val -= 1
    
  3. 使用线程池提高效率 避免线程创建和销毁的开销
    import concurrent.futures
    def func(num):
        return num * 2
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        results = [executor.submit(func, i) for i in range(10)]
        for future in concurrent.futures.as_completed(results):
            print(future.result())
    

利用协程提高程序并发性

  1. 使用asyncio模块创建协程
    import asyncio
    async def func():
        print("hello, world!")
    asyncio.run(func())
    
  2. 使用asyncio中的Future对象 类似于线程中的future,用于异步调用函数
    import asyncio
    async def func():
        return 1 + 2
    coroutine = func()
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(coroutine)
    print(result)
    
  3. 使用asyncio中的Event Loop 协程的调度中心,负责任务的调度和切换
    import asyncio
    async def func():
        print("A")
        await asyncio.sleep(1)
        print("B")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(func(), func(), func()))
    

比较多线程和协程

  1. 线程和协程的区别 线程是系统级别的,协程是程序级别的;线程切换需要系统介入,协程切换只需要程序自己控制
  2. 适用场景的区别 IO密集型任务适合使用协程,CPU密集型任务适合使用多线程
  3. 优缺点的区别 多线程优点:多核CPU有优势,缺点:线程切换需要系统介入,开销大 协程优点:切换开销小,缺点:单线程无法利用多核CPU