Python线程传递参数 [英] Python threads passing parameters

查看:72
本文介绍了Python线程传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些参数传递给服务器踏板,但我不知道如何传递?

I'm trying to passing some parameter to the server tread, but I have no idea how?

这是我的代码:

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

this is the MCRequestHandler

class MCRequestHandler( SocketServer.BaseRequestHandler ):

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

    def setup( self ):
        clientsLock.acquire()

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

How can I pass one or two parameter to the MCRequestHandler class?

推荐答案

我觉得ThreadingTCPServer的第二个参数是工厂:

I think the second parameter of ThreadingTCPServer is a factory:

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

你可以在这里做的是你自己的工厂.类将构造一个可调用对象.当对象被调用时,它将使用给工厂的参数初始化 MCRequestHandler:

What you could do is your own factory here. Class will contstuct a callable object. when the object is called it will initialize MCRequestHandler with parameters given to the factory:

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)

这篇关于Python线程传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆