0

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

Community
  • 1
  • 1
Spock
  • 51
  • 6
  • 1
    *Previous answers on this topic advise threading module but I have tried it and it does not work* What did you try, Provide a [MCVE]. Also take a look at [Dead simple example of using Multiprocessing Queue, Pool and Locking](http://stackoverflow.com/q/20887555) – Bhargav Rao Jun 15 '16 at 08:07
  • thread.start_new_thread(main()) thread.start_new_thread(face()) This does not run both of them simultaneously. Instead, finishes them up one by one. I tried threading module http://www.tutorialspoint.com/python/python_multithreading.htm But the result was the same. – Spock Jun 15 '16 at 08:25
  • If you aren't using ROS anyway, don't use rospy only running things in parallel. This is not what it is meant for and it will give you a unnecessary dependency on ROS. – luator Jun 16 '16 at 12:25

1 Answers1

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()
Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
  • A big thanks SIr! I had tried the multiprocessing module out using the target keyword but it had not worked. A follow-up question, though. Is name a necessary argument? Thanks – Spock Jun 15 '16 at 08:34
  • No it isn't: in the [example in 16.6.1.1](https://docs.python.org/2/library/multiprocessing.html) you can see `Process(target=f, args=('bob',))`. So you can remove the name part! I will update my answer :) – Nander Speerstra Jun 15 '16 at 08:37
  • For me, this was also the example I was looking for. Like @Spock I looked at proposed duplicates but wasn't able to get it working untill I implemented the code above – Kenneth Breugelmans Jan 16 '18 at 13:59