0

I'm trying to run 2 separate processes in my python application. So I have code like this:

from multiprocessing import Process

def f1():
  while 1:  
    print('Hello')

def f2():
  while 1:
    print('Goodbye')


def main():
    p1 = Process(target=f1, args=())
    p1.start()
    p1.join()

    p2 = Process(target=f2, args=())
    p2.start()
    p2.join()

if __name__ == '__main__':
    main()

This code does nothing on my machine, it doesn't produce any output. I thought initially that maybe it was an IDE-related problem, but it's the same on both my IDEs, PyScripter and IDLE.
Any ideas, why this doesn't print anything?

5
  • 3
    Also, p2 will never start as it will be perpetually waiting on p1 to join Commented Mar 6, 2014 at 18:40
  • 1
    It does print 'Hello' until the end of time due to your while 1: loop. Commented Mar 6, 2014 at 18:43
  • No, it doesn't print anything, even the same code without loops. Commented Mar 6, 2014 at 18:44
  • Could you add a print('something') statement inside main() function? Does it print anything? Commented Mar 6, 2014 at 18:48
  • Then your problem is probably a duplicate of this: stackoverflow.com/questions/4355878/… Commented Mar 6, 2014 at 18:54

2 Answers 2

3

How about using Queue?

from multiprocessing import Process, Queue

def f1(q):
  while 1:
    q.put('Hello')

def f2(q):
  while 1:
    q.put('Goodbye')


def main():
  q = Queue()
  p1 = Process(target=f1, args=(q,))
  p1.start()

  p2 = Process(target=f2, args=(q,))
  p2.start()

  while True:
     try:
        print q.get()
     except:
        break

if __name__ == '__main__':
  main()
Sign up to request clarification or add additional context in comments.

Comments

2

You should save it and run outside the IDE:

C:\> python multi.py

then it infinitely prints out Hello. You should change your main to see both Hello and Goodbye:

def main():
  p1 = Process(target=f1, args=())
  p2 = Process(target=f2, args=())

  p1.start()
  p2.start()

  p1.join()
  p2.join()

Then you have a little happy race condition that constantly prints out GHoodbyeello because both processes use the same stdout resource concurrently.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.