0

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

Litinum
  • 21
  • 1
  • 4

1 Answers1

3

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)

Rob Bricheno
  • 4,467
  • 15
  • 29
  • 1
    Also note, that the reason that this does not fail is because the method returns `None`, and providing `None` as the `target` of the `Thread` constructor is valid, even though it is rather useless. "target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called." https://docs.python.org/3/library/threading.html#threading.Thread – flakes Sep 22 '19 at 08:06
  • I worked, but i need rest of the program to wait until these 2 finish, i added "t1.join()" and "t2.join()" but it there is error now "t1.join() AttributeError: 'NoneType' object has no attribute 'join'" – Litinum Sep 22 '19 at 08:20
  • 1
    @Litinum `Thread` constructor returns the thread that you can call join on. `start` is a method that returns `None`. Break it into three statements. `t1 = Thread(...); t1.start(); t1.join();` – flakes Sep 22 '19 at 08:33
  • Updated answer to use `join()` – Rob Bricheno Sep 22 '19 at 08:35