Parallel Processing on Python [duplicate]

2019-09-09 00:54发布

问题:

This question already has an answer here:

  • How to use threading in Python? 20 answers
  • Dead simple example of using Multiprocessing Queue, Pool and Locking 5 answers

I am a beginner in python and multiprocessing so if the question seems naive please forgive me. I have two functions that I want to run at the same time. One is an openCV implementation of face recognition and the other is a standard python code.

def main():
    does(s) # a function call 

def face():
    recog.main() #another call

As you can guess, both the functions are the final end user functions that one has to call to implement the task. I want them both to run simutaneously.

Previous answers on this topic advise threading module but I have tried it and it does not work. The first func. to be called is executed first and then the second one. A friend of mine recommended rospy module. Is it the only way? Thanks in anticipation.

EDIT: In the answer to this, Make 2 functions run at the same time , a user has written that threading actually won't make two functions run at the same time

回答1:

I use the multiprocessing module for running two functions parallel. For what I did (changed to your situation):

import multiprocessing

def main():
    does(s) # a function call 

def face():
    recog.main() #another call

# Initiate two workers for the two functions
workerMAIN = multiprocessing.Process(target=main)
workerFACE = multiprocessing.Process(target=face)

# Start the workers
workerMAIN.start()
workerFACE.start()

# Wait until the functions have finished
workerMAIN.join()
workerFACE.join()