scoketServer 多线程同步
开发过程中,为了实现不同的客户端同一时刻只能有一个使用共同数据。
首先,明确一点,在scoketServer中,每当有一个客户端连接成功后都会为每个客户端创建一个线程。
为了让这些多线程之间能够同步执行,我的做法是:再创建一个线程类,这个线程类中做一些我的项目需要做的事情,,当某个客户端想成使用到这个线程时,给当前线程加锁,运行完成后释放锁,
请指教
详细步骤请看注释:
#coding=gbk __author__ = 'kaikai' import Queue import threading import time import SocketServer
#全局线程锁 threadLock = threading.Lock()
#全局数据队列 data = Queue.Queue()
#工作线程类, class testThead(threading.Thread): global data def __init__(self): threading.Thread.__init__(self) def begin_test(self): self.start() def run(self): global threadLock threadLock.acquire() # 从队列中取出连接和数据 if data.qsize()>0: this_receive = data.get() else: print "data size is empty !" return # 解析数据,获得连接和数据 # 使用当前数据的conn this_conn = this_receive.keys()[0] this_data = this_receive[this_conn] # 释放锁 threadLock.release() def send_msg(self,conn,msg): try: conn.sendall(msg) except Exception as e: print "send " + str(msg) +"fail !!!!!!!!!!!!!!" def recv_msg(self,conn): try: recv_msg = conn.recv(2048) return recv_msg except Exception as e: print " recv msg fail !!!!!!!!!!" return None # 每有一个客户端生成一个线程。所有线程调用同一个测试线程,如果测试线程在锁定中,则进入等待。 class MyServer(SocketServer.BaseRequestHandler): def send_msg(self,conn,msg): try: conn.sendall(msg) except Exception as e: print "send " + str(msg) +"fail !!!!!!!!!!!!!!" def recv_msg(self,conn): try: recv_msg = conn.recv(2048) return recv_msg except Exception as e: print " recv msg fail !!!!!!!!!!" def handle(self): global data # 获得连接 conn = self.request print "client connect!" # 循环接受客户端数据 while True: # 接受客户端发送过来的参数 receive_data = self.recv_msg(conn) print receive_data # 如果参数为空,返回报错 结束循环 if not receive_data: print "can not get data form client ! " break print "data size put before: " + str(data.qsize()) # 将连接和数据添加到队列中 放入连接可以保证在另一个线程中直接使用连接给相应客户端发送或者接受数据。同时保证数据与客户端的一一对应 data.put({conn:receive_data}) print "data size put aftter: " + str(data.qsize()) # 初始化测试线程 testThead_this = testThead() # 开始测试线程 testThead_this.begin_test() # testThead_this.start() # 等待测试线程执行结束 testThead_this.join() print "this test end " if __name__ == "__main__" : try: server = SocketServer.ThreadingTCPServer(('192.168.100.100',56780),MyServer) server.timeout = 100 print "Server run success !!!! " server.serve_forever() except Exception as e: print "Server run failed !!!!\n error: " + str(e)