我正在尝试为我的项目创建一些多处理代码。我创造了一段我想做的事情。但是它并没有按照我的期望工作。你能告诉我这个有什么问题吗。在
from multiprocessing import Process, Pipe
import time
class A:
def __init__(self,rpipe,spipe):
print "In the function fun()"
def run(self):
print"in run method"
time.sleep(5)
message = rpipe.recv()
message = str(message).swapcase()
spipe.send(message)
workers = []
my_pipe_1 = Pipe(False)
my_pipe_2 = Pipe(False)
proc_handle = Process(target = A, args=(my_pipe_1[0], my_pipe_2[1],))
workers.append(proc_handle)
proc_handle.run()
my_pipe_1[1].send("hello")
message = my_pipe_2[0].recv()
print message
print "Back in the main function now"
按ctrl-c时显示的跟踪:
^{pr2}$当我运行上面的代码时,主进程在调用“proc”之后不会继续_手柄。运行". 为什么会这样?在
您误解了如何使用
Process
。您正在创建一个Process
对象,并将其作为target
传递给它,但是target
意味着要传递一个可调用的(通常是一个函数)Process.run
然后执行。所以在您的例子中,它只是在Process.run
内实例化A
,就这样。在您应该将您的
A
类改为Process
子类,并直接实例化它:不过,姆吉尔森是对的。您应该调用
start()
,而不是run()
,使A.run
在子进程中执行。在有了这些变化,程序对我来说很好:
^{pr2}$尝试一下这个,我想这是因为你调用的是^{} 而不是{a2}。在
前者是流程将要执行的活动,后者实际上安排在一个单独的进程上调用
run
。换句话说,您永远不会分叉进程,因此my_pipe_1[1]
没有其他进程可与之通信,因此它挂起。在相关问题 更多 >
编程相关推荐