我确信这有一个非常简单的解决方案 - 我只是不知道在哪里寻找它。
我有一种方法如下:
@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现在继承自Threading:
class Clientthread(threading.Thread):
def __init__(self,clientsocket, clientnumber, server):
threading.Thread.__init__(self)
def run(self):
from modules.logic import game
'''
as clientthread inherits from threading.Thread, this is this Thread's run-method.
All it does is start the thread with the processkeysmethod - by now.
'''
logging.getLogger(__name__).info("Runmethode des Clientsockets läuft")
logging.getLogger(__name__).info("Daten aus dem Client werden verarbeitet")
while True:
try:
Clientthread.prepareDataforClient(self)
Clientthread.processkeys(self)
except Exception as e:
print e
现在,当然,每个Clientthread实例都在同一个全局数据上工作。
我现在的问题是,如何同步?实际上,其中一个Clientthreads无法知道有多少其他Clientthreads技术上,它可以是从零开始的任何数字。
有没有一种简单的方法可以解决这个问题
答案 0 :(得分:0)
您需要一个互斥锁来同步线程对共享资源的访问权限。然后,您可以像这样使用互斥锁:
with mtx:
# access shared data
那就是说,还有一些问题:
ClassName.function(self)
可能更好地写为self.function()
。最后,我不确定我是否可以正确解释,我宁愿不从Thread派生。该对象不是线程,而是表示一个,类似于文件。创建一个将创建一个线程,但例如摧毁一个不会阻止线程,因此我发现派生不自然。这看起来像这样:
s = accept(...)
th = threading.Thread(target=connection_handler_function, args=(s,))
th.daemon = True # you probably want that
th.start()