从父进程

时间:2015-10-12 14:24:23

标签: python parallel-processing network-programming multiprocessing

我正在创建一个简单的TCP服务器作为存根,因此我可以测试操作一块测试设备的脚本,而无需在那里安装设备。服务器应该坐在那里等待连接,然后维护和更新状态变量(只是6个整数的列表)以响应它接收的命令。然后,父进程(例如单元测试类)应该能够在任何时候询问状态。

服务器的界面应该简单如下:

server = StubServer()
server.start()
'''
the client script connects with the server and
some stuff happens to change the state
'''
newState = server.getState() # newState = [93,93,93,3,3,45] for example
server.terminate()

我已经将Multiprocessing.Process子类化了,我可以启动服务器没问题。当我第一次测试它时,在getState()方法中我只返回了实例变量_state,但我发现这始终只是初始状态。经过一番挖掘,我无法找到任何类似的例子。很多关于子类化过程,但不是这个特定的问题。最后我将下面的内容放在一起使用内部Queue()来存储状态,但这对我来说看起来很混乱和笨重。有更好的方法吗?

import socket
from multiprocessing import Process, Queue

class StubServer(Process):

    _port = 4001
    _addr = '' # all addresses 0.0.0.0
    _sock = None
    _state = []
    _queue = None

    def __init__(self, initState=[93,93,93,93,93,93]):
        super(StubServer, self).__init__()
        self._queue = Queue()
        self._state = initState

    def run(self):
        # Put the state into the queue
        self._queue.put(self._state)
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.bind((self._addr, self._port))
        self._sock.listen(1)

        waitingForConnection = True
        '''
        Main loop will continue until the connection is terminated. if a connection is closed, the loop returns
        to the start and waits for a new connection. This means multiple tests can be run with the same server
        '''
        while 1:
            # Wait for a connection, or go back and wait for a new message (if a connection already exists)
            if waitingForConnection:
                waitingForConnection = False
                conn, addr = self._sock.accept()
            chunk = ''
            chunks = []
            while '\x03' not in chunk: # '\x03' is terminating character for a message
                chunk = conn.recv(8192)
                if not chunk: # Connection terminated, start the loop again and wait for a new connection
                    waitingForConnection = True
                    break
                chunks.append(chunk)
            message = ''.join(chunks)
            # Now do some stuff to parse the message, and update the state if we received a command
            if isACommand(message):
                _updateState(message)
        conn.close()
        return

    def getState(self):
        # This is called from the parent process, so return the object on the queue
        state = self._queue.get()
        # But put the state back in the queue again so it's there if this method is called again before a state update
        self._queue.put(state)
        return state

    def _updateState(self, message):
        # Do some stuff to figure out what to update then update the state
        self._state[updatedElementIndex] = updatedValue
        # Now empty the queue and put the new state in the queue
        while not self._queue.empty():
            self._queue.get()
        self._queue.put(self._state)
        return

3 个答案:

答案 0 :(得分:0)

顾名思义,multiprocessing使用不同的流程。在某些时候,调用fork()并且子进程复制父进程的内存,并且子进程拥有自己的内存,而不是与父进程共享。

不幸的是,你使用tools available在进程之间共享内存,导致你提到的代码开销。

您可以查找使用共享内存进行并行处理的其他方法,但请注意,在线程/进程/节点/等之间共享内存绝非易事。

答案 1 :(得分:0)

您可以将存根服务器的状态转储到文件,并随时从单元测试中读取它。它是测试需求的非常简单的解决方案。

您需要做的所有事情:

  • filename作为参数传递给构造函数
  • 使用初始值
  • 调用_updateState
  • 重写_updateState以将状态写入filename。最好在filename附近创建一个新文件并替换它。如果你担心原子性。

答案 2 :(得分:0)

感谢Felipe,我的问题主要是“有比使用队列更好的方式”。就像我在问题中所做的那样。经过一番研究(提到共享内存提示)后,我发现共享数组对于这种情况要好得多:

import socket
from multiprocessing import Process, Array

class StubServer(Process):

    _port = 4001
    _addr = '' # all addresses 0.0.0.0
    _sock = None
    _state = None
    _queue = None

    def __init__(self, initState=[93,93,93,93,93,93]):
        super(StubServer, self).__init__()
        self._state = Array('i', initState) # Is always a 6 element array

    def run(self):
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.bind((self._addr, self._port))
        self._sock.listen(1)

        waitingForConnection = True
        '''
        Main loop will continue until process is terminated. if a connection is closed, the loop returns
        to the start and waits for a new connection. This means multiple tests can be run with the same server
        '''
        while 1:
            # Wait for a connection, or go back and wait for a new message (if a connection already exists)
            if waitingForConnection:
                waitingForConnection = False
                conn, addr = self._sock.accept()
            chunk = ''
            chunks = []
            while '\x03' not in chunk: # '\x03' is terminating character for a message
                chunk = conn.recv(8192)
                if not chunk: # Connection terminated, start the loop again and wait for a new connection
                    waitingForConnection = True
                    break
                chunks.append(chunk)
            message = ''.join(chunks)
            # Now do some stuff to parse the message, and update the state if we received a command
            if isACommand(message):
                _updateState(message)
        conn.close()
        return

    def getState(self):
        # Aquire the lock return the contents of the shared array
        with self._state.get_lock():
            return self._state[:6] # This is OK because we know it is always a 6 element array
        return state

    def _updateState(self, message):
        # Do some stuff to figure out what to update then..
        # Aquire the lock and update the appropriate element in the shared array
        with self._state.get_lock():
            self._state[updatedElementIndex] = updatedValue
        return

这是一种享受,更优雅。谢谢你的帮助