Python 3 control multiprocessing

This is the place for queries that don't fit in any of the other categories.

Python 3 control multiprocessing

Postby tbaror » Sat Aug 10, 2013 6:55 pm

I am trying to write function using Python multiprocessing that i can control it and pass "command" to cleanly terminate the process. I looked for few examples and tried it out ,but didn't seems to work fro me
So basically i need to to run separate process function code that doing some while loop action and when needed stop it by passing somehow command and exit
Please advice
Thanks

example 1


Code: Select all
from multiprocessing import Process, Queue

def start_process(queue):
  while True:
    try:
        m = queue.get()
        if m == 'exit':
            print ('cleaning up worker...')
            # add here your cleaning up code
            break
        else:
            print (m)
    except KeyboardInterrupt:
        print ('ignore CTRL-C from worker')


if __name__ == '__main__':
  queue = Queue()

  process = Process(target=start_process, args=(queue,))
  process.start()

  queue.put(12)

  try:
    process.join()
  except KeyboardInterrupt:
    print ('wait for worker to cleanup...')
    queue.put('exit')
    process.join()


example 2


Code: Select all
import multiprocessing
    import time

    class MyProcess(multiprocessing.Process):

        def __init__(self, ):
            multiprocessing.Process.__init__(self)
            self.exit = multiprocessing.Event()

        def run(self):
            while not self.exit.is_set():
                pass
            print ("You exited!")

        def shutdown(self):
            print ("Shutdown initiated")
            self.exit.set()


    if __name__ == "__main__":
        process = MyProcess()
        process.start()
        print ("Waiting for a while")
        time.sleep(3)
        process.shutdown()
        time.sleep(3)
        print ("Child process state: %d" % process.is_alive())
tbaror
 
Posts: 13
Joined: Sun Jul 07, 2013 8:06 pm

Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], W3C [Linkcheck] and 4 guests