我肯定有一个非常简单的解决办法-我只是不知道在哪里找它。在
我有一种方法可以做到:
@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——从技术上讲,它可以是从零开始的任何数量。在
有没有简单的方法来解决这个问题
您需要一个互斥体来同步线程对共享资源的访问。然后,您可以像这样使用互斥体:
也就是说,还有几个问题要问:
ClassName.function(self)
可能最好写成self.function()
。在最后,我不确定是否能正确解释,我宁愿不从线程中派生。对象不是线程,而是代表一个线程,类似于文件。创建一个线程将创建一个线程,但销毁一个线程并不能停止线程,因此我发现派生是不自然的。然后如下所示:
^{pr2}$相关问题 更多 >
编程相关推荐