基于Python的多处理模块,我需要做以下事情:
- 创建一个不断运行的进程,该进程可以被特定事件中断。
- 在这个过程中,接收来自客户端的消息,并将此消息传递给对象实例的处理程序方法。
基本代码如下(省略了一些细节)。问题是我尝试调用实例方法(self.enroll(message),但没有效果,正如预期的那样。我知道原因 - 进程使用自己的内存等 - 我已经实现了中提出的解决方案Can't pickle <type 'instancemethod'> 当使用 python 的多处理 Pool.map()来解决腌制有界方法的问题时,以及使用 Manager、Queue、Pool 尝试不同的方法......因为没有工作,我决定将代码尽可能“原始”,以便您理解我的意图。欢迎任何帮助。
class DistManager:
def __init__(self, name, network_address, password):
self.name = name
self.network_address = network_address
self.password = password
self.distribution_clients = {}
def _run_distribution_process(self):
import select
while not self.should_stop_distribution_service.is_set():
(sread, swrite, sexc) = select.select([self.distribution_listener], [], [], 0)
if (sread):
connection = self.distribution_listener.accept()
serialized_message = connection.recv() # currently only receiving
connection.close()
message = pickle.loads(serialized_message)
self.enroll(message) # THE PROBLEM IS HERE
def start_distribution_service(self, distribution_port):
self.distribution_port = distribution_port
# patch for making Listener work with select.select during run
Listener.fileno = lambda self: self._listener._socket.fileno()
self.distribution_listener = Listener(address=(self.network_address, self.distribution_port),
authkey=self.password)
self.should_stop_distribution_service = Event()
self.distribution_process = Process(name='Distribution Runner', target=self._run_distribution_process)
self.distribution_process.daemon = True
self.distribution_process.start()
def stop_distribution_service(self):
from time import sleep
self.should_stop_distribution_service.set()
sleep(1)
self.distribution_listener.close()
self.distribution_process.terminate()
return self.distribution_process.exitcode
def _enroll_distribution_client(self, identifier, network_address, phone_number):
self.distribution_clients[identifier] = (network_address, phone_number)
def enroll(self, message):
if type(message.content) is tuple:
self._enroll_distribution_client(message.generator_identifier, message.content[0], message.content[1])
else:
raise TypeError("Tuple expected")
return message.code