繁体   English   中英

单独脚本上的Python多线程

[英]Python Multi Thread on separate script

我有将新客户端运行到新线程中的脚本

thread1 = threading.Thread(target=loop_logic,args=(client1,))
thread2 = threading.Thread(target=loop_logic,args=(client2,))

他们总是在True条件下运行

假设我的脚本是server.py

然后我想使client.py在运行时向server.py添加新线程,因此当我执行client.py时它将添加:

thread3 = threading.Thread(target=loop_logic,args=(client3,))

等等。 我可以用什么方法做到这一点?

您可以为客户端和服务器创建类,将对服务器的引用传递给每个新客户端,并为服务器类添加一个用于创建新客户端的函数。 这是一个非常基本的例子

import threading

class Server(object):
    def __init__(self):
        self.chilren = []
        self.threads = []
    def NewChild(self, client_info):
        child = Client(self, client_info)  # self is a reference to the current server instance
        child_thread = threading.thread(target=child.run, args=(,))
        self.children.append(child)
        self.threads.append(child_thread)
        child_thread.start()
    def run(self):
        pass
        # Whatever server code should go here

class Client(object):
    def __init__(self, parent, info): # info is a stand-in for arguments
        self.parent = parent
        self.info = info
    def run(self):
        self.parent.NewChild(other_info)
        # Any other processing too

在此示例中, logic_loopClient.run方法替换。 在该函数中run任何处理都将在run发生,并且任何参数都将作为info参数传递到类中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM