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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

it is just printing "Error: unable to start thread" and also can you please make a program with my functions
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.

2 Comments

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 It looks like you are using windows and there it's mandatory to use if __name__ .... For more information see here. I will edit the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.