2

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!

William Le
  • 825
  • 1
  • 9
  • 16
  • 1
    Does this answer your question? [Python: Executing multiple functions simultaneously](https://stackoverflow.com/questions/18864859/python-executing-multiple-functions-simultaneously) – Faraaz Kurawle Feb 16 '22 at 05:42
  • @FaraazKurawle yes exactly what I'm looking for but I was unfortunate. After dozens time of searching I did not find this useful post for some reasons – William Le Feb 16 '22 at 06:15

3 Answers3

1
  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 

rzlvmp
  • 7,512
  • 5
  • 16
  • 45
  • Thank you so much I found a workaround by using multiple processes ```p = Process(...)```. If you don't mind, could you tell me what is the difference between using async function vs multiprocesses? – William Le Feb 16 '22 at 06:17
  • 1
    @SeanWilliam it is better to search for an [answer](https://stackoverflow.com/questions/27435284/multiprocessing-vs-multithreading-vs-asyncio-in-python-3) on this common question in the internet – rzlvmp Feb 16 '22 at 06:21
  • Gosh how come when I search for the exact terms these useful posts don't show up at all like yours :( – William Le Feb 16 '22 at 06:23
  • @Sean William, can you please share the workaround you found using multiple processes ? – Timeless Aug 14 '22 at 19:32
1

You can also use threading:-


def func1():
    print('Working')

def func2():
    print("Working")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()
CodeWithYash
  • 223
  • 1
  • 15
  • Thank you for your suggesstion. I am now informed of 3 possible solutions: async functions, multiple processes, and threading. Which one would you recommend? – William Le Feb 16 '22 at 06:19
  • 1
    multithreading programming is all about concurrent execution of different functions. Async programming is about non-blocking execution between functions. – CodeWithYash Feb 16 '22 at 06:40
1

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)
Faraaz Kurawle
  • 1,085
  • 6
  • 24