关于异步并发的几点疑惑

一、某一Task在挂起时,被挂起的子任务是不是在新的线程或进程里继续执行,直到返回结果,通知主线程

这个问题迷惑了我很久,所以需要通过代码实验一下:

  • 编写一个协程,在协程中获取当前的线程和进程ID
  • 在另一个协程中调用上一个协程,并获取当前协程的线程ID和进程ID
  • 封装为Task,纳入事件循环中运行,查看主线程的线程ID和进程ID
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    import asyncio
    import time
    import os
    import psutil
    import threading

    async def get_runtime_info():
    pid = os.getpid()
    p = psutil.Process(pid)
    await asyncio.sleep(1)
    print(f"Process info:{p.ppid}")
    print(f"Threading info:{threading.get_ident()}")

    async def test():
    await get_runtime_info()

    async def main():
    pid = os.getpid()
    p = psutil.Process(pid)
    print(f"Main Process info:{p.ppid}")
    print(f"Main Threading info:{threading.get_ident()}")
    tasks = []
    for i in range(5):
    tasks.append(asyncio.create_task(test()))

    res = await asyncio.gather(*tasks)

    print(res)


    asyncio.run(main())

执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
Main Process info:<bound method Process.ppid of psutil.Process(pid=4940, name='python.exe', started='10:27:49')>
Main Threading info:6460
Process info:<bound method Process.ppid of psutil.Process(pid=1760, name='python.exe', started='10:22:57')>
Threading info:5716
Process info:<bound method Process.ppid of psutil.Process(pid=1760, name='python.exe', started='10:22:57')>
Threading info:5716
Process info:<bound method Process.ppid of psutil.Process(pid=1760, name='python.exe', started='10:22:57')>
Threading info:5716
Process info:<bound method Process.ppid of psutil.Process(pid=1760, name='python.exe', started='10:22:57')>
Threading info:5716
Process info:<bound method Process.ppid of psutil.Process(pid=1760, name='python.exe', started='10:22:57')>
Threading info:5716
[None, None, None, None, None]

可见,任务均在同一线程,同一进程内完成。

assert表达式

python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达式为假。可以理解assert断言语句为 raise-if-not,用来测试表示式,其返回值为假,就会触发异常。