如何检查功能是否阻塞?

How to check if function is blocking or not?

我正在使用其中包含同步代码的异步工作流。我如何检查同步函数是否阻塞,以确保在执行期间没有任何中断。


async def download_upload_xmls_async(message,count,id,conn1,cursor1,conn2,cursor2):
    # SOME CODE
    xml = await req(urlX, headers)

    print('Got message')

    write(message_count, id, conn1, cursor1)
    print('Wrote progress')

    send_message("Send" + xml, id, conn2, cursor2)
    print('Sent message')

    write_locally(data)

    await message.ack()

在上面的代码中,我如何检查函数 write 和 send_message 是非阻塞的?他们与数据库一起工作,我无法访问以检查一切是否按预期工作。我还可以假设,如果函数 write_locally 正常工作,我以前的函数也可以正常工作吗?

函数 write 和 send_message 做几乎相同的事情——它们获取数据并使用传递给它们的连接和游标在 PostgreSQL 数据库上执行查询。函数 write_locally 写入 csv 文件。

def send_message(message, id, con, cur, **nargs):
    params = {
              #some params
             }
    union_params= {**params, **nargs}
    data = json.dumps(union_params, ensure_ascii=False)
    cur.execute(
                #Query
                )
    con.commit()

我还要补充一点,连接和游标是用aiopg创建的,所以他们所有的方法都是协程。

如果连接和游标有协程方法,那么send_message写的不会阻塞事件循环。

但是,它不会任何事情,因为它无法等待它调用的协程。它需要用 async def 定义,并且需要 awaitcur.execute(...)cur.commit() 的调用。 download_upload_xmls_async 同样未能等待 send_message。正确的代码应该是这样的:

async def download_upload_xmls_async(message, count, id, conn1, cursor1, conn2, cursor2):
    ... some code here ...
    # note the await
    await send_message("Send" + xml, id, conn2, cursor2)
    # write_locally doesn't need to be a coroutine because
    # it (presumably) doesn't block    
    write_locally(data)
    await message.ack()

# note "async def"
async def send_message(message, id, con, cur, **nargs):
    params = {
              #some params
             }
    union_params= {**params, **nargs}
    data = json.dumps(union_params, ensure_ascii=False)
    # note the await
    await cur.execute(
                #Query
                )
    await con.commit()