Python編程scoketServer實(shí)現(xiàn)多線程同步實(shí)例代碼
本文研究的主要是Python編程scoketServer實(shí)現(xiàn)多線程同步的相關(guān)內(nèi)容,具體介紹如下。
開發(fā)過程中,為了實(shí)現(xiàn)不同的客戶端同一時(shí)刻只能有一個(gè)使用共同數(shù)據(jù)。
雖說用Python編寫簡(jiǎn)單的網(wǎng)絡(luò)程序很方便,但復(fù)雜一點(diǎn)的網(wǎng)絡(luò)程序還是用現(xiàn)成的框架比較好。這樣就可以專心事務(wù)邏輯,而不是套接字的各種細(xì)節(jié)。SocketServer模塊簡(jiǎn)化了編寫網(wǎng)絡(luò)服務(wù)程序的任務(wù)。同時(shí)SocketServer模塊也是Python標(biāo)準(zhǔn)庫(kù)中很多服務(wù)器框架的基礎(chǔ)。
網(wǎng)絡(luò)服務(wù)類:
SocketServer提供了4個(gè)基本的服務(wù)類:
TCPServer針對(duì)TCP套接字流
UDPServer針對(duì)UDP數(shù)據(jù)報(bào)套接字
UnixStreamServer和UnixDatagramServer針對(duì)UNIX域套接字,不常用。
首先,明確一點(diǎn),在scoketServer中,每當(dāng)有一個(gè)客戶端連接成功后都會(huì)為每個(gè)客戶端創(chuàng)建一個(gè)線程。
為了讓這些多線程之間能夠同步執(zhí)行,我的做法是:再創(chuàng)建一個(gè)線程類,這個(gè)線程類中做一些我的項(xiàng)目需要做的事情,,當(dāng)某個(gè)客戶端想成使用到這個(gè)線程時(shí),給當(dāng)前線程加鎖,運(yùn)行完成后釋放鎖。
請(qǐng)指教
詳細(xì)步驟請(qǐng)看注釋:
#coding=gbk __author__ = 'kaikai' import Queue import threading import time import SocketServer #全局線程鎖 threadLock = threading.Lock()#全局?jǐn)?shù)據(jù)隊(duì)列 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() # 從隊(duì)列中取出連接和數(shù)據(jù) if data.qsize()>0: this_receive = data.get() else: print "data size is empty !" return # 解析數(shù)據(jù),獲得連接和數(shù)據(jù) # 使用當(dāng)前數(shù)據(jù)的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 # 每有一個(gè)客戶端生成一個(gè)線程。所有線程調(diào)用同一個(gè)測(cè)試線程,如果測(cè)試線程在鎖定中,則進(jìn)入等待。 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!" # 循環(huán)接受客戶端數(shù)據(jù) while True: # 接受客戶端發(fā)送過來的參數(shù) receive_data = self.recv_msg(conn) print receive_data # 如果參數(shù)為空,返回報(bào)錯(cuò) 結(jié)束循環(huán) if not receive_data: print "can not get data form client ! " break print "data size put before: " + str(data.qsize()) # 將連接和數(shù)據(jù)添加到隊(duì)列中 放入連接可以保證在另一個(gè)線程中直接使用連接給相應(yīng)客戶端發(fā)送或者接受數(shù)據(jù)。同時(shí)保證數(shù)據(jù)與客戶端的一一對(duì)應(yīng) data.put({conn:receive_data}) print "data size put aftter: " + str(data.qsize()) # 初始化測(cè)試線程 testThead_this = testThead() # 開始測(cè)試線程 testThead_this.begin_test() # testThead_this.start() # 等待測(cè)試線程執(zhí)行結(jié)束 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)
總結(jié)
以上就是本文關(guān)于Python編程scoketServer實(shí)現(xiàn)多線程同步實(shí)例代碼的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
Python 進(jìn)程之間共享數(shù)據(jù)(全局變量)的方法
今天小編就為大家分享一篇Python 進(jìn)程之間共享數(shù)據(jù)(全局變量)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07python爬蟲開發(fā)之使用python爬蟲庫(kù)requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實(shí)例
這篇文章主要介紹了python爬蟲開發(fā)之使用python爬蟲庫(kù)requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實(shí)例,需要的朋友可以參考下2020-03-03OpenCV角點(diǎn)檢測(cè)的實(shí)現(xiàn)示例
角點(diǎn)通常被定義為兩條邊的交點(diǎn),本文主要介紹了OpenCV角點(diǎn)檢測(cè)的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03Python 2.7.x 和 3.x 版本的重要區(qū)別小結(jié)
這篇文章主要介紹了Python 2.7.x 和 3.x 版本的重要區(qū)別小結(jié),需要的朋友可以參考下2014-11-11python模塊簡(jiǎn)介之有序字典(OrderedDict)
字典是Python開發(fā)中很常用的一種數(shù)據(jù)結(jié)構(gòu),但dict有個(gè)缺陷(其實(shí)也不算缺陷),迭代時(shí)并不是按照元素添加的順序進(jìn)行,可能在某些場(chǎng)景下,不能滿足我們的要求。2016-12-12python如何使用雙線性插值計(jì)算網(wǎng)格內(nèi)數(shù)據(jù)
這篇文章主要介紹了python如何使用雙線性插值計(jì)算網(wǎng)格內(nèi)數(shù)據(jù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08pytorch-autograde-計(jì)算圖的特點(diǎn)說明
這篇文章主要介紹了pytorch-autograde-計(jì)算圖的特點(diǎn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05解決運(yùn)行django程序出錯(cuò)問題 ''str''object has no attribute''_meta''
這篇文章主要介紹了解決運(yùn)行django程序出錯(cuò)問題 'str'object has no attribute'_meta',具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07