0

我正在尝试使用 Python 多处理编写函数,我可以控制它并传递“命令”来干净地终止进程。我找了几个例子并尝试了它,但似乎对我不起作用
所以基本上我需要运行单独的进程函数代码来执行一些while循环动作,并在需要时通过以某种方式传递命令并退出来停止它请建议谢谢

示例 1

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()

示例 2

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())
4

1 回答 1

0

这两个例子对我来说都很好——也许你误解了它们应该如何工作?

在第一个示例中,当主线程运行时,它启动子线程并发送 12。然后它等待加入子线程。那时一切都停滞不前,因为孩子正在等待“退出”。但是如果你然后点击 ctrl-C 'exit' 被发送,孩子退出,第二次加入成功:

> python3.3 example1.py                                                    
12                                                                              
^Cignore CTRL-C from worker                                                     
wait for worker to cleanup...                                                   
cleaning up worker...                                                           
>

如果您只想让父母发送“退出”,然后一切都结束,请使用:

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')
  print('goodbye cruel world')


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

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

  queue.put(12)
  print ('sending exit')
  queue.put('exit')
  process.join()

这使:

> python3.3 my-example.py 
sending exit
12
cleaning up worker...
goodbye cruel world
> 

你的第二个例子也有效(缩进固定):

> python3.3 example2.py 
Waiting for a while
Shutdown initiated
You exited!
Child process state: 0
>

(稍等一下)。不知道你还能在这里期待什么。

于 2013-08-10T20:24:21.027 回答