簡體   English   中英

Python套接字多進程工作池

[英]Python socket multiprocessing pool of workers

我需要通過套接字接收連接,讀取輸入數據,進行長時間的艱苦計算,然后發送答案。 我同時知道的查詢可能很多(例如100),因為GIL我無法使用普通線程,而是嘗試將C ++與boost:threads和boost:python一起使用,並在每個線程中運行python的子解釋器。 但是無論如何,它並不能同時100%使用所有內核。

因此,我決定使用多處理,但創建了一個靜態的工作人員計數池,以通過隊列為這些請求提供服務。 這樣,我們就不會浪費時間派生一個進程,並且我們不會同時有100個或更多的進程,而只有靜態計數。

我是Python的新手,主要是我使用C ++

所以現在我有了這段代碼,但是它不起作用。 連接打開並立即關閉,我不知道為什么:

#!/usr/bin/env python   
import os
import sys
import SocketServer
import Queue
import time
import socket
import multiprocessing
from multiprocessing.reduction import reduce_handle
from multiprocessing.reduction import rebuild_handle 

class MultiprocessWorker(multiprocessing.Process):

    def __init__(self, sq):

        self.SLEEP_INTERVAL = 1

        # base class initialization
        multiprocessing.Process.__init__(self)

        # job management stuff
        self.socket_queue = sq
        self.kill_received = False

    def run(self):
        while not self.kill_received:
            try:     
                h = self.socket_queue.get_nowait()          
                fd=rebuild_handle(h)
                client_socket=socket.fromfd(fd,socket.AF_INET,socket.SOCK_STREAM)
                #client_socket.send("hellofromtheworkerprocess\r\n")
                received = client_socket.recv(1024)
                print "Recieved on client: ",received
                client_socket.close()

            except Queue.Empty:
                pass

            #Dummy timer
            time.sleep(self.SLEEP_INTERVAL)

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        #self.data = self.request.recv(1024).strip()
        #print "{} wrote:".format(self.client_address[0])
        #print self.data
        # just send back the same data, but upper-cased
        #self.request.sendall(self.data.upper())

        #Either pipe it to worker directly like this
        #pipe_to_worker.send(h) #instanceofmultiprocessing.Pipe
        #or use a Queue :)

        h = reduce_handle(self.request.fileno())
        socket_queue.put(h)


if __name__ == "__main__":

    #Mainprocess
    address =  ('localhost', 8082)
    server = SocketServer.TCPServer(address, MyTCPHandler)
    socket_queue = multiprocessing.Queue()

    for i in range(5):
        worker = MultiprocessWorker(socket_queue)
        worker.start()

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

有沒有不使用的理由

def reduce_socket(s):
    ...

def rebuild_socket(ds):
    ...

看來您可以這樣做:

import copyreg
copyreg.pickle(type(socket.socket), reduce_socket, rebuild_socket)

然后將套接字傳遞給隊列。

這些是建議。 他們有幫助嗎?

嘗試這個:

def handle(self):
    h = reduce_handle(self.request.fileno())
    socket_queue.put(h)
    self.request.close()

注意self.request.close()的添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM