Python中的线程如何等待未知数量的其他线程

2024-09-30 14:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我肯定有一个非常简单的解决办法-我只是不知道在哪里找它。在

我有一种方法可以做到:

 @staticmethod  
def serverstart(self):
    '''
    This binds the serverobject to a port (here: 50001) and creates a list of clients.
    For each client, a new clientthread object is created. There exist two different lists, one for the 
    sockets (literally) and one for the clientthreads
    '''
    logging.getLogger(__name__).info("Servergestartet(Verbindung usw)") 
    self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.server.bind(("", 50001)) 
    self.server.listen(1)
    #the list for the sockets
    self.clients = []
    #the list for the clientthreads
    self.clientthreads = []
    #hallo = "hallo" 
    self.clientnumber = 0          

    try: 
        while True: 
            lesen, schreiben, oob = select.select([self.server] + self.clients, 
                                         [], [])

            for sock in lesen: 
                if sock is self.server: 
                    client, addr = self.server.accept() 
                    myclient = clientthread.Clientthread(client, self.clientnumber, self)
                    self.clientnumber= self.clientnumber+1
                    myclient.start()
                    self.clients.append(client) 
                    self.clientthreads.append(myclient)
                    print "+++ Client %s verbunden" % addr[0] 
                #else: 
                    #nachricht = sock.recv(1024) 
                    #ip = sock.getpeername()[0] 
                    #if nachricht: 
                        #print "[%s,%d] %s" % (ip, self.clients.index(sock),nachricht) 
                    #else: 
                        #print "+++ Verbindung zu %s beendet" % ip 
                        #sock.close() 
                        #self.clients.remove(sock) 
    finally:
        logging.getLogger(__name__).info("serverstart ist durchgelaufen")

因此,每当新客户机连接时,都会创建一个新的Clientthread实例。在

Clientthread现在从线程继承:

^{pr2}$

当然,Clientthread的每个实例都在相同的全局数据上工作。在

我现在的问题是,如何同步?实际上,一个Clientthreads无法知道还有多少个Clientthreads——从技术上讲,它可以是从零开始的任何数量。在

有没有简单的方法来解决这个问题


Tags: theselfclientforserversocketlistclients
1条回答
网友
1楼 · 发布于 2024-09-30 14:29:28

您需要一个互斥体来同步线程对共享资源的访问。然后,您可以像这样使用互斥体:

with mtx:
    # access shared data

也就是说,还有几个问题要问:

  • 你到底需要什么还不是百分之百清楚。如果一个RLock解决了你的问题,那么这与你所写而不仅仅是阅读的陈述有什么对应呢?在
  • 此外,请清理代码,删除不必要的东西,如注释代码。在
  • 缩进是关闭的,这是Python中的一个错误。在
  • @staticmethod的用法很奇怪。在
  • 调用ClassName.function(self)可能最好写成self.function()。在
  • 使用super()调用基类的init函数。在
  • 如果在客户机和clientthreads之间有1:1的关系,那么将它们聚合到一个公共类中可以更好地进行建模。在

最后,我不确定是否能正确解释,我宁愿不从线程中派生。对象不是线程,而是代表一个线程,类似于文件。创建一个线程将创建一个线程,但销毁一个线程并不能停止线程,因此我发现派生是不自然的。然后如下所示:

^{pr2}$

相关问题 更多 >