Exemplo n.º 1
0
class ThreadSupport(object):
    """ The decorator is used to add a multi-thread support to
    DHT server.

    Parameters:
      - thread_num: the number of thread to handle message from remote
      host, which will pass to thread_pool.WorkerManger __init__ method.
      - q_size: the workers number of thread_pool.WorkManger.work_queue,
      which will pass to thread_pool.WorkerManger __init__ method.
    """

    def __init__(self, cls, thread_num=6, q_size=200):
        self._cls = cls
        self._worker_manager = WorkerManager(thread_num, q_size)

    def __call__(self, *args, **kwargs):

        def _serve_forever(this):
            this.bootstrap()
            while 1:
                try:
                    (data, address) = this.socket.recvfrom(this.buffer_size)
                    self._worker_manager.add_task(
                        this.handle_recv, data, address)
                except socket.error:
                    pass

        def _stopd(this):
            self._worker_manager.kill_all_task()
            this.socket.close()

        # Replace `serve_forever` and `stopd` method of `DHT`.
        # Use thread pool to handle message in `serve_forever`.
        self._cls.serve_forever = _serve_forever
        self._cls.stopd = _stopd
        dht = self._cls(*args, **kwargs)
        return dht