Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python function to run in background

I have two functions, "one" and "two". I want function "one" to run in the background as two runs. Basically, one executes, and while it’s waiting, execute two.

import time

def one(msg, a):
    time.sleep(a)
    print(msg)
def two(msg, a):
    time.sleep(a)
    print(msg)

one("Hello, ", 2) # Run this in the background as the other function runs
two("World!", 1)

I tried coroutines but it didn’t really work out for me because one ran after the other.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use multi-threading to have one function run in the background. You can use multiprocessing as well, but in most scenarios, simply creating a thread is better than creating an entire separate process. In your case, you can change your code to look like this:

import time, threading

def one(msg, a):
    time.sleep(a)
    print(msg)
def two(msg, a):
    time.sleep(a)
    print(msg)

thread = threading.Thread(target=one, args=("Hello, ", 2))
thread.start()
two("World!", 1)

If however, you want to use multi-processing, you can use this code instead:

import time
from multiprocessing import Process

def one(msg, a):
    time.sleep(a)
    print(msg)

def two(msg, a):
    time.sleep(a)
    print(msg)

if __name__ == '__main__':
    p1 = Process(target=one, args=("Hello, ", 2))
    p1.start()
    
    p2 = Process(target=two, args=("World!", 1))
    p2.start()

Both of these will achieve the same result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading