gpt4 book ai didi

Python线程传递参数

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:16 25 4
gpt4 key购买 nike

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

这是我的代码:

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 类?

最佳答案

我认为 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)

关于Python线程传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com