python 使用多線程創(chuàng)建一個Buffer緩存器的實現(xiàn)思路
這幾天學習人臉識別的時候,雖然運行的沒有問題,但我卻意識到了一個問題
在圖片進行傳輸?shù)臅r候,GPU的利用率為0
也就是說,圖片的傳輸速度和GPU的處理速度不能很好銜接
于是,我打算利用多線程開發(fā)一個buffer緩存
實現(xiàn)的思路如下
定義一個Buffer類,再其構造函數(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)
th1 = threading.Thread(target=put)
th2 = threading.Thread(target=get)
th1.start()
th2.start()
th1.join()
th2.join()

總結
到此這篇關于python 使用多線程創(chuàng)建一個Buffer緩存器的文章就介紹到這了,更多相關python 多線程Buffer緩存器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python3中dict.keys().sort()用不了的解決方法
本文主要介紹了python3中dict.keys().sort()用不了的解決方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
Python+OpenCV實現(xiàn)鼠標畫瞄準星的方法詳解
所謂瞄準星指的是一個圓圈加一個圓圈內(nèi)的十字線,就像玩射擊游戲狙擊槍開鏡的樣子一樣。本文將利用Python+OpenCV實現(xiàn)鼠標畫瞄準星,感興趣的可以嘗試一下2022-08-08
Python中實現(xiàn)限定抽獎次數(shù)的機制的項目實踐
抽獎系統(tǒng)作為吸引用戶、提高用戶參與度和活躍度的重要手段,本文主要介紹了Python中實現(xiàn)限定抽獎次數(shù)的機制的項目實踐,具有一定的參考價值,感興趣的可以了解一下2024-05-05
解決Numpy報錯:ImportError: numpy.core.multiarray faile
這篇文章主要介紹了解決Numpy報錯:ImportError: numpy.core.multiarray failed問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
OpenCV中resize函數(shù)插值算法的實現(xiàn)過程(五種)
最新版OpenCV2.4.7中,cv::resize函數(shù)有五種插值算法:最近鄰、雙線性、雙三次、基于像素區(qū)域關系、蘭索斯插值。感興趣的可以了解一下2021-06-06

