創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務器提供商,新人活動買多久送多久,劃算不套路!

這篇文章主要介紹python中多線程如何搭建Buffer緩存器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
這幾天學習人臉識別的時候,雖然運行的沒有問題,但我卻意識到了一個問題
在圖片進行傳輸?shù)臅r候,GPU的利用率為0
也就是說,圖片的傳輸速度和GPU的處理速度不能很好銜接
于是,我打算利用多線程開發(fā)一個buffer緩存
實現(xiàn)的思路如下
定義一個Buffer類,再其構(gòu)造函數(shù)中創(chuàng)建一個buffer空間(這里最好使用list類型)
我們還需要的定義線程鎖LOCK(數(shù)據(jù)傳輸和提取的時候會用到)
因為需要兩種方法(讀數(shù)據(jù)和取數(shù)據(jù)),所以我們需要定義兩個鎖
實現(xiàn)的代碼如下:
#-*-coding:utf-8-*-
import threading
class Buffer:
def __init__(self,size):
self.size = size
self.buffer = []
self.lock = threading.Lock()
self.has_data = threading.Condition(self.lock) # small sock depand on big sock
self.has_pos = threading.Condition(self.lock)
def get_size(self):
return self.size
def get(self):
with self.has_data:
while len(self.buffer) == 0:
print("I can't go out has_data")
self.has_data.wait()
print("I can go out has_data")
result = self.buffer[0]
del self.buffer[0]
self.has_pos.notify_all()
return result
def put(self, data):
with self.has_pos:
#print(self.count)
while len(self.buffer)>=self.size:
print("I can't go out has_pos")
self.has_pos.wait()
print("I can go out has_pos")
# If the length of data bigger than buffer's will wait
self.buffer.append(data)
# some thread is wait data ,so data need release
self.has_data.notify_all()
if __name__ == "__main__":
buffer = Buffer(3)
def get():
for _ in range(10000):
print(buffer.get())
def put():
a = [[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9]]
for _ in range(10000):
buffer.put(a)
th2 = threading.Thread(target=put)
th3 = threading.Thread(target=get)
th2.start()
th3.start()
th2.join()
th3.join()
標題名稱:python中多線程如何搭建Buffer緩存器-創(chuàng)新互聯(lián)
URL標題:http://chinadenli.net/article6/eogog.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、小程序開發(fā)、品牌網(wǎng)站設計、做網(wǎng)站、外貿(mào)網(wǎng)站建設、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)