【问题标题】:python async - functions not starting at the same timepython async - 函数不同时启动
【发布时间】:2023-02-16 20:41:53
【问题描述】:

我这里有以下程序

`
import datetime
import asyncio
import time
import math

async def count1():
    s = 0
    print('start time count 1: ' +str(datetime.datetime.now()))
    for i in range(100000000):
        s += math.cos(i)
    print('end time count 1: ' +str(datetime.datetime.now()))
    return s

async def count2():
    s = 0
    print('start time count 2: ' +str(datetime.datetime.now()))
    for i in range(1000000):
        s += math.cos(i)
    print('end time count 2: ' +str(datetime.datetime.now()))
    return s

async def main():
    start_time = time.time()
    task = asyncio.gather(count1(), count2())
    results = await task
    end_time = time.time()
    print(f"Result 1: {results[0]}")
    print(f"Result 2: {results[1]}")
    print(f"Total time taken: {end_time - start_time:.2f} seconds")

asyncio.run(main())

输出是

start time count 1: 2023-02-16 12:26:19.322523
end time count 1: 2023-02-16 12:26:40.866866
start time count 2: 2023-02-16 12:26:40.868166
end time count 2: 2023-02-16 12:26:41.055005
Result 1: 1.534369444774577
Result 2: -0.28870546796843
Total time taken: 21.73 seconds

我试图让 count1() 和 count2() 同时开始工作,因为它看到它没有发生输出。 count2() 仅在 count1() 结束后开始,我不确定为什么。

我还尝试将 main() 中的行替换为:

task1 = asyncio.create_task(count1())
task2 = asyncio.create_task(count2())
result1 = await task1
result2 = await task2

not 也不会导致 count1() 和 count2() 同时启动。

【问题讨论】:

    标签: python asynchronous


    【解决方案1】:

    async 本质上是 cooperative multitaskingawaits 都不是函数,因此只要它们运行并且不屈服于其他函数,它们就会占用整个过程。

    你可以添加一个战略

    if i % 10000 == 0:
        await asyncio.sleep(0)
    

    在循环中,因此它们“让位”给其他异步协程。

    【讨论】:

      猜你喜欢
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2020-05-18
      • 2017-02-28
      相关资源
      最近更新 更多