如何检查功能是否阻塞?

时间:2019-04-03 12:13:19

标签: python python-asyncio python-multithreading

我正在使用异步工作流,其中包含同步代码。如何检查同步功能是否阻塞,以确保在执行过程中没有中断。

SELECT OrderLine.ProductID, SUM(OrderLineQuantity)FROM OrderLine Inner Join [Order] ON OrderLine.OrderID = [Order].OrderID  WHERE OrderStatus = 'Completed'

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

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

trainable_model = keras.models.load_model(
            path, custom_objects={'Attention': Attention, 'MultiTaskLoss': MultiTaskLoss}, compile=True) # tried with compile=False
        trainable_model.summary()
        input = trainable_model.inputs[0]
        i_output = trainable_model.get_layer('i_output').output
        t_output = trainable_model.get_layer('t_output').output
        testable_model = keras.models.Model(
            inputs=input, outputs=[i_output, t_output])
       # Tried without below for loop.
        for l in testable_model.layers:
            l_name = l.name
            l.set_weights(trainable_model.get_layer(name=l_name).get_weights())
        testable_model.compile('adam', loss={
                               'i_output': 'categorical_crossentropy', 't_output': 'categorical_crossentropy'})
        return testable_model

我还必须添加,该连接和游标是使用aiopg创建的,因此它们的所有方法都是协程。

1 个答案:

答案 0 :(得分:1)

如果连接和游标具有协程方法,则编写的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()
相关问题