0

Ok so, I searched for this answer all over the internet but I am getting the answers which just run these functions one after the other

import time

def a():
    time.sleep(5)
    print("lmao")
def b():
    time.sleep(5)
    print("not so lmao huh")

I want "lmao" and "not so lmao" to be printed at the same time ( after 5 seconds) The solutions which I saw all over the internet just printed "lmao" after 5 seconds of starting the program and "not so lmao huh" after 5 seconds of a()

Chinar
  • 7
  • 4

2 Answers2

1

As Far as i understood your question you should use threading for it. you can refer this guide Threading. If you need any clarification feel free to comment.

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass
satvik
  • 95
  • 9
  • it is just printing "Error: unable to start thread" and also can you please make a program with my functions – Chinar Dec 03 '20 at 06:28
0

If you want to run your functions parallel, then you may want to use the multiprocessing.

You can create some processes and execute your function in them.

For example:

import time
import multiprocessing as mp
from multiprocessing.context import Process


def a():
    time.sleep(5)
    print("lmao")


def b():
    time.sleep(5)
    print("not so lmao huh")

if __name__ == '__main__':
    p1: Process = mp.Process(target=a)
    p2: Process = mp.Process(target=b)
    p1.start()
    p2.start()
    p1.join()
    p2.join()

There are also such API for coroutines and tasks and threading. Maybe you will find them more convenient.

Valerii Boldakov
  • 1,751
  • 9
  • 19
  • well it just gives an error ................. An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. – Chinar Dec 03 '20 at 06:26
  • @Chinar It looks like you are using windows and there it's mandatory to use `if __name__ ...`. For more information see [here](https://stackoverflow.com/questions/18204782/runtimeerror-on-windows-trying-python-multiprocessing). I will edit the answer. – Valerii Boldakov Dec 03 '20 at 06:43