【问题标题】:python3 code not running concurrently Asynciopython3代码没有同时运行Asyncio
【发布时间】:2021-06-24 07:53:45
【问题描述】:

请帮我找出错误在哪里,我想并行运行两个函数。太棒了

import asyncio
import time

async def test1():
    for i in range(10):
        print(f"First function {i}")

async def test2():
    for i in range(10):
        print(f"Second function {i}")

async def main():
    print(f"started at {time.strftime('%X')}")
    F = asyncio.create_task(test1())
    S = asyncio.create_task(test2())
    tasks = (F, S)

    await asyncio.gather(*tasks)
    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

相反,我得到的输出与并行执行没有任何关系:

    started at 10:42:53
First function 0
First function 1
First function 2
First function 3
First function 4
First function 5
First function 6
First function 7
First function 8
First function 9
Second function 0
Second function 1
Second function 2
Second function 3
Second function 4
Second function 5
Second function 6
Second function 7
Second function 8
Second function 9
finished at 10:42:53

【问题讨论】:

  • 你的异步函数不会等待任何东西。这意味着它们永远不会将控制权交还给事件循环。这就是它们同步运行的原因。您可以添加 await asyncio.sleep(0),但如果您的任务都是 CPU 密集型的,那么 multiprocessingconcurrent.futures.ProcessPoolExecutor 将提供比 asyncio 更好的价值。

标签: python-3.x debugging concurrency parallel-processing python-asyncio


【解决方案1】:

好的,最后我重写了我的代码以使用线程,它运行良好,但我不知道如何从线程函数中捕获返回值,所以起初我的代码看起来像这样:

import threading
import time

def test1():
    for i in range(10):
        print(f"First function {i}")
    return 11

def test2():
    for i in range(10,20):
        print(f"Second function {i}")

def main():
    t = time.time()
    t1 = threading.Thread(target=test1)
    t2 = threading.Thread(target=test2)
    t1.start()
    t2.start()
    print(t1.join())
    t2.join()
    print("Woaahh!! My work is finished..")
    print("I took " + str(time.time() - t))

main() 

在这个线程的帮助下,我对返回值进行了一些更改,here

所以现在我的代码如下所示:

import time
import concurrent.futures

def test1():
    for i in range(10):
        print(f"First function {i}")
    return 11

def test2():
    for i in range(10,20):
        print(f"Second function {i}")
    return 12

def main():
    t = time.time()
 
    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(test1)
        future2 = executor.submit(test2)
        return_value = future.result()
        rv= future2.result()
        print(return_value)
        print(rv)
        
        print("Woaahh!! My work is finished..")
        print("I took " + str(time.time() - t))

main()

【讨论】:

    【解决方案2】:

    我不知道你的代码有什么问题,但如果你想并行运行,我想你可以尝试这样的事情,通过使用线程?

    threading.Thread(target=test1).start()
    threading.Thread(target=test2).start()
    

    https://docs.python.org/fr/3/library/threading.html

    【讨论】:

    • 谢谢,我误解了单词并发的含义。现在有了“导入线程”,一切都按我的预期工作。
    【解决方案3】:

    这是另一个使用队列处理函数输出代码的示例

    import threading
    import time
    import queue
    
    def test1(q):
        for i in range(10):
            print(f"First function {i}")
        q.put(1)
    
    def test2(q):
        for i in range(10,20):
            print(f"Second function {i}")
        q.put(2)
    
    def main():
        q = queue.Queue()
        t = time.time()
        t1 = threading.Thread(target=test1, args=(q, ))
        t2 = threading.Thread(target=test2, args=(q, ))
        t1.start()
        t2.start()
        print(t1.join())
        t2.join()
        print("Woaahh!! My work is finished..")
        print("I took " + str(time.time() - t))
    
        while not q.empty():
            print(q.get())
    
    main() 
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多