Reputation: 13
I'm making a virtual assistant using Python. For that I need one main thread running continuously which is required for Speech recognition and want to run other threads like actions after detecting speech to run in background.
For the tasks like timer, I want to make it running in background while the main thread is running, so that I can perform other tasks even when the timer is running... and after reaching the time it should return it as tts
to main thread
current structure I'm using is
main.py
-> class Main()
->Running logger in background // which is meant to exit with mainLoop
-> and Command() loop for speech recognition continuously
->`which links to Brain.py to timer.py
Upvotes: 0
Views: 4290
Reputation: 11593
A few words about multithreading
vs multiprocessing
:
In multithreading you start a thread in the current process. Python runs (through the global interpreter lock) threads in short sequential order, never really in parallel. The upside is that threads can access the same variables (i.e. share memory).
On the other side in multiprocessing you run a new process (in the OS it appears as a separate program). They can really run in parallel but sharing variables is a lot more tricky (and much slower as well).
For your use case it seems that not two things are "CPU bound" i.e. it will not be the case that two things will need the CPU for 100% at the same time. In this situation, multithreading is probably the better solution, that is you should go for James Lim's solution.
If you still want to go for multiprocessing, then the following code could be your basic setup for timer. For the speech recognition function it would be accordingly (espeically the part about returning the list should be sufficient for returning tts from the speech recognition):
import multiprocessing
import time
def timer_with_return(seconds, return_list):
time.sleep(seconds)
return_list.append('foo')
if __name__ == "__main__":
# variables by manager are shared among process
# e.g. for return values
manager = multiprocessing.Manager()
timer_return = manager.list()
timer = multiprocessing.Process(target=timer_with_return, args=(3, timer_return))
timer.start()
while True:
time.sleep(1)
if not timer.is_alive():
break
print("timer is still running")
timer.join() # make sure the process is really finished
print("timer finished, return value is {}".format(timer_return))
Running this produces:
timer is still running
timer is still running
timer is still running
timer finished, return value is ['foo']
Upvotes: 1