Python线程传递参数

时间:2011-06-17 18:06:09

标签: python multithreading

我正在尝试将一些参数传递给服务器,但我不知道怎么做?

这是我的代码:

HOST, PORT = socket.gethostbyname( socket.gethostname() ), 31000
self.server = SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )
ip, port = self.server.server_address        
self.server_thread = threading.Thread( target = self.server.serve_forever )

这是MCRequestHandler

class MCRequestHandler( SocketServer.BaseRequestHandler ):

    global Lidars, clientsLock, postbox
    Lidars = []
    postbox = {}
    clientsLock = threading.RLock()    

    def setup( self ):
        clientsLock.acquire()

如何将一个或两个参数传递给MCRequestHandler类?

1 个答案:

答案 0 :(得分:3)

我认为ThreadingTCPServer的第二个参数是工厂:

  SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )

你能做的就是你自己的工厂。类将构造一个可调用对象。当调用该对象时,它将使用给出的参数初始化MCRequestHandler:

class MyRequestHandlerFactory(object):

  def __init__(self, param1, param2): 
            self.param1 = param1
            self.param2 = param2

  def __call__(self):
            handler = MCRequestHandler()
            handler.param1 = param1
            handler.param2 = param2

然后初始化:

  factory = MyRequestHandlerFactory("x", "y")
  SocketServer.ThreadingTCPServer( ( HOST, PORT ), factory)