Python:从内部发送消息到进程

时间:2012-03-03 16:53:06

标签: python python-multithreading

这个问题可能不清楚 - 如果是这样,可能是因为我不完全不知道如何提出这个问题 - 但是这里有:

我有一个Python类,我想从中调用一个函数。

该类无法访问该函数应该操作的数据 - 基本上,我希望该类向另一个调用该函数的进程发送消息。类似的东西:

from multiprocessing import Process

class Foo():
   def bar(phonenumber):
      do_something()
      send_message(phonenumber)

def daemon(data, phonenumber):
   while nothing_receivied(phonenumber):
      do_nothin()
      also_do_not_consume_too_much_CPU()
   if message_received(phonenumber):
      function(data)

p = Process(target=daemon, args=(data, phonenumber))
p.start()
p.join()

调用Foo.bar(phonenumber)应该会对function执行data产生额外影响 - 这是如何实现的?

干杯!

1 个答案:

答案 0 :(得分:0)

如果您特意尝试使用multiprocessing模块,则应该考虑使用队列/管道。 http://docs.python.org/library/multiprocessing.html#pipes-and-queues

您的守护程序代码中您希望在不消耗太多CPU的情况下执行任何操作的部分是尝试从队列中获取项目,或者轮询管道以获取数据并阻塞,直到某些内容准备就绪。队列或管道的另一端只是将数据放入队列中,这些队列充当了send_message概念的角色。

如果您想要一个更强大的异步解决方案,您还应该查看Twisted库:http://twistedmatrix.com/trac/

这将允许您在更高级别定义一个服务,该服务具有带处理程序的事件循环以处理传入连接。

最后,如果您只想在同一个脚本中使用简单的解决方案,而不是基于网络的任何内容,您可以轻松地使用线程模块:http://docs.python.org/library/threading.html。并使用Queue.Queue守护程序阻止get(),send_message()执行put()

相关问题