【问题标题】:Print message while a function is running in Python with AsyncIO使用 AsyncIO 在 Python 中运行函数时打印消息
【发布时间】:2022-02-16 18:28:52
【问题描述】:

我正在尝试创建一个持续打印的打印函数,例如“Hello World”,而另一个函数(称为 miner)并行运行,并且这两个函数必须同时结束。

这是我正在研究的比特币挖矿实时成本测量器。

我发现 python as asyncio 并尝试使用它,但是我无法在矿工功能结束的同时停止打印功能。定时器函数打印一次,等待矿工函数。

import asyncio
import time  
from datetime import datetime
class Test2:  
    async def miner(self):
        await asyncio.sleep(5)
        return 0
    async def timer(self):  
        while True:
            print("\n Hello World \n")
            time.sleep(1)

t2 = Test2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(t2.miner(), t2.timer()))

我尝试了并发任务,但两个函数没有并行运行(定时器和矿工)。 你能告诉我一个解决这个问题的方法吗? 谢谢!

【问题讨论】:

标签: python python-asyncio


【解决方案1】:
  1. time.sleep() 不是异步函数,所以timer 进程在结束之前会锁定其他操作(但不幸的是它是无止境的)
  2. 您可以添加共享触发器变量以在矿工完成时停止timer
import asyncio

class Test2:

    is_ended = False

    async def miner(self):
        await asyncio.sleep(5)
        self.is_ended = True
        print("\n I'm done \n")
        return 0

    async def timer(self):  
        while True:
            if self.is_ended:
               print('\n Bye Bye \n')
               break
            print("\n Hello World \n")
            await asyncio.sleep(1)

t2 = Test2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(t2.miner(), t2.timer()))

 Hello World 


 Hello World 


 Hello World 


 Hello World 


 Hello World 


 I'm done 


 Bye Bye 

【讨论】:

  • 非常感谢我找到了使用多个进程p = Process(...) 的解决方法。如果你不介意,你能告诉我使用异步函数和多进程有什么区别吗?
  • @SeanWilliam 最好在网上搜索一下answer 这个常见问题
  • 天哪,当我搜索这些有用的帖子的确切术语时,这些有用的帖子根本不像你的那样出现:(
【解决方案2】:

你也可以使用线程:-


def func1():
    print('Working')

def func2():
    print("Working")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

【讨论】:

  • 感谢您的建议。我现在知道了 3 种可能的解决方案:异步函数、多进程和线程。你会推荐哪一个?
  • 多线程编程是关于不同功能的并发执行。异步编程是关于函数之间的非阻塞执行。
【解决方案3】:

您可以使用multiprocessingthreading

from multiprocessing import Process
index=0
def func1():
    global index
    print ('start func1')
    while index< 20:
        index+= 1
    print ('end func1')

def func2():
    global rocket
    print ('start func2')
    while index< 10:
        index+= 1
    print ('end func2')

if __name__=='__main__':
    p1 = Process(target = func1)
    p1.start()
    p2 = Process(target = func2)
    p2.start()

用于踩踏

import threading
x = threading.Thread(target=func1)
y = threading.Thread(target=func1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2020-08-01
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多