Search code examples
pythonmultithreadingmultiprocessingpyttsx

Need to run 2 functions at the same time but, but they only run one after another


I have 2 functions

def Print_Out(string):
    typing_speed = Engine.getProperty('rate') #wpm
    for c in string:
        print(c, end='')
        time.sleep(random.random()*10.0/typing_speed)
    print('')

Which will print text slowly at 200 wpm and another function "Say", which will read that text to the user (using pyttsx3).

I tried using multithreading

threading.thread(target = Print_Out(Response)).start()
threading.thread(target = Say(Response)).start()

(and i also tried without ".start()" at the end which still runs the functions) And i tried multiprocessing but im not sure i did it right and i cant provide code for that cause i just took something that i found and tried using it here

I need them to run in parallel, as the text prints out, the voice is saying it, but what ends up happening is it prints out the text slowly and then it reads it (or other way around, depends how are they placed in the code). There are no errors


Solution

  • When you tried to make the threaded version you actually passed the result of calling the intended targets (with Response as the argument) instead of the functions.

    So the functions were first getting called, waiting to return, then the response (whatever that was) passed as the target argument to Thread.

    Try this instead:

    t1 = threading.Thread(target=Print_Out, args=(Response,))
    t2 = threading.Thread(target=Say, args=(Response,))
    t1.start()
    t2.start()
    # And wait for the threads to finish
    t1.join()
    t2.join()
    

    (i.e. pass the functions themselves)