有没有一种方法可以将变量发送到特定任务?

时间:2020-01-29 10:36:35

标签: python python-3.x asynchronous python-asyncio

我希望能够向特定的asyncio任务(或类似任务)发送变量或其他内容,以便它可以跳过睡眠部分。这是我正在使用的结构:

async def someFunction():
    x = 'something'
    variable_i_need = False
    asyncio.create_task(someLoop(x, variable_i_need))

async def someLoop(x, variable_i_need):
    while True:
        print(x)
        for i in range(60):
            if variable_i_need:
                break
            await asyncio.sleep(1)

async def someOtherFunction():
    variable_i_need = True
    #Send this to specific task running someLoop()

我是否可以通过某种方式执行此操作,或者可以使用与x个其他任务相同的循环来更新一个任务?我可以使用全局变量来做到这一点,但是它将更新所有任务,而不仅仅是一个。

1 个答案:

答案 0 :(得分:1)

我会使用全局词典

说variable_i_need = {},其键=任务名称,值为True或False

然后从someloop进行检查

if variable_i_need{x}: break

然后使用:

async def someOtherFunction(x):
    variable_i_need{x} = True