这个Python多处理代码有什么问题?

2024-09-30 01:24:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的项目创建一些多处理代码。我创造了一段我想做的事情。但是它并没有按照我的期望工作。你能告诉我这个有什么问题吗。在

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”之后不会继续_手柄。运行". 为什么会这样?在


Tags: run代码importselfmessagetimemydef
2条回答

您误解了如何使用Process。您正在创建一个Process对象,并将其作为target传递给它,但是target意味着要传递一个可调用的(通常是一个函数)Process.run然后执行。所以在您的例子中,它只是在Process.run内实例化A,就这样。在

您应该将您的A类改为Process子类,并直接实例化它:

#!/usr/bin/python

from multiprocessing import Process, Pipe
import time

class A(Process):
      def __init__(self,rpipe,spipe):
          print "In the function fun()"
          super(A, self).__init__()
          self.rpipe = rpipe
          self.spipe = spipe

      def run(self):
           print"in run method"
           time.sleep(5)
           message = self.rpipe.recv()
           message = str(message).swapcase()
           self.spipe.send(message)

if __name__ == "__main__":    
    workers = []
    my_pipe_1 = Pipe(False)
    my_pipe_2 = Pipe(False)
    proc_handle = A(my_pipe_1[0], my_pipe_2[1])
    workers.append(proc_handle)
    proc_handle.start()
    my_pipe_1[1].send("hello")
    message = my_pipe_2[0].recv()
    print message
    print "Back in the main function now"

不过,姆吉尔森是对的。您应该调用start(),而不是run(),使A.run在子进程中执行。在

有了这些变化,程序对我来说很好:

^{pr2}$

尝试一下这个,我想这是因为你调用的是^{}而不是{a2}。在

前者是流程将要执行的活动,后者实际上安排在一个单独的进程上调用run。换句话说,您永远不会分叉进程,因此my_pipe_1[1]没有其他进程可与之通信,因此它挂起。在

相关问题 更多 >

    热门问题