Print message while a function is running in Python with AsyncIO

Viewed 433

I'm trying to create a print function that keeps printing, for example, 'Hello World', while another function (called miner) is running in parallel, and both functions must end at the same time.

enter image description here

This is for a real-time cost measurer for bitcoin mining that I'm working on.

I found that python as asyncio and tried to use it, however I couldn't get the print function to stop at the same time the miner function ends. The timer function printed once and waited for the miner function.

enter image description here

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()))

I tried concurrent tasks, but both function does not run in parallel (timer and miner). Could you show me a way to solve this? Thank you!

3 Answers
  1. time.sleep() is not asynchronous function so timer process locks other operations before it ends (but unfortunately it is endless)
  2. You may add shared trigger variable to stop timer when miner complete
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 

You can also use threading:-


def func1():
    print('Working')

def func2():
    print("Working")

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

You can use multiprocessing or threading

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()

for treading

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