Python多进程问题进程未启动
我写了这段代码,我想有一个主线程来启动多个子进程,生成一个侦听器线程来等待kill消息子进程工作,但testprocess不运行没有错误有什么想法吗Python多进程问题进程未启动,python,multiprocessing,Python,Multiprocessing,我写了这段代码,我想有一个主线程来启动多个子进程,生成一个侦听器线程来等待kill消息子进程工作,但testprocess不运行没有错误有什么想法吗 from multiprocessing import Process, Pipe from threading import Thread import time Alive = True def listener_thread(conn): #listens for kill from main
from multiprocessing import Process, Pipe
from threading import Thread
import time
Alive = True
def listener_thread(conn): #listens for kill from main
global Alive
while True:
data = conn.recv()
if data == "kill":
Alive = False #value for kill
break
def subprocess(conn):
t = Thread(target=listener_thread, args=(conn,))
count = 0
t.start()
while Alive:
print "Run number = %d" % count
count = count + 1
def testprocess(conn):
t = Thread(target=listner_thread, args=(conn,))
count = 0
t.start()
while Alive:
print "This is a different thread run = %d" % count
count = count + 1
parent_conn, child_conn = Pipe()
p = Process(target=subprocess, args=(child_conn,))
p2 = Process(target=testprocess, args=(child_conn,))
runNum = int(raw_input("Enter a number: "))
p.start()
p2.start()
time.sleep(runNum)
parent_conn.send("kill") #sends kill to listener thread to tell them when to stop
p.join()
p2.join()
testprocess
中的输入错误会使函数提前退出
listner\u线程
应该是listener\u线程
如果注释掉子流程
相关代码并运行代码,您将看到以下错误:
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "t.py", line 25, in testprocess
t = Thread(target=listner_thread, args=(conn,))
NameError: global name 'listner_thread' is not defined
哦,哇,它就在我面前。现在它们都可以运行了,但过程会无限返回到调试阶段,谢谢@KyleSponable,顺便说一句,你需要调用
parent\u conn.send(“kill”)
两次。所以我需要调用它的次数与打开线程的次数相同?@KyleSponable,是的<一个进程中的代码>活动不会影响另一个进程中的活动
。