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.
>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.