python 使用多線程創(chuàng)建一個(gè)Buffer緩存器的實(shí)現(xiàn)思路
這幾天學(xué)習(xí)人臉識別的時(shí)候,雖然運(yùn)行的沒有問題,但我卻意識到了一個(gè)問題
在圖片進(jìn)行傳輸?shù)臅r(shí)候,GPU的利用率為0
也就是說,圖片的傳輸速度和GPU的處理速度不能很好銜接
于是,我打算利用多線程開發(fā)一個(gè)buffer緩存
實(shí)現(xiàn)的思路如下
定義一個(gè)Buffer類,再其構(gòu)造函數(shù)中創(chuàng)建一個(gè)buffer空間(這里最好使用list類型)
我們還需要的定義線程鎖LOCK(數(shù)據(jù)傳輸和提取的時(shí)候會(huì)用到)
因?yàn)樾枰獌煞N方法(讀數(shù)據(jù)和取數(shù)據(jù)),所以我們需要定義兩個(gè)鎖
實(shí)現(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()
總結(jié)
到此這篇關(guān)于python 使用多線程創(chuàng)建一個(gè)Buffer緩存器的文章就介紹到這了,更多相關(guān)python 多線程Buffer緩存器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3中dict.keys().sort()用不了的解決方法
本文主要介紹了python3中dict.keys().sort()用不了的解決方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12python安裝/卸載模塊方法步驟詳解(附詳細(xì)圖解)
在日常工作中會(huì)需要安裝或者卸載Python模塊.于是我整理了一下,下面這篇文章主要給大家介紹了關(guān)于python安裝/卸載模塊的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01Python+OpenCV實(shí)現(xiàn)鼠標(biāo)畫瞄準(zhǔn)星的方法詳解
所謂瞄準(zhǔn)星指的是一個(gè)圓圈加一個(gè)圓圈內(nèi)的十字線,就像玩射擊游戲狙擊槍開鏡的樣子一樣。本文將利用Python+OpenCV實(shí)現(xiàn)鼠標(biāo)畫瞄準(zhǔn)星,感興趣的可以嘗試一下2022-08-08一文解密Python函數(shù)的實(shí)現(xiàn)原理
函數(shù)是任何一門編程語言都具備的基本元素,它可以將多個(gè)要執(zhí)行的操作組合起來,一個(gè)函數(shù)代表了一系列的操作。那就來看看Python函數(shù)的實(shí)現(xiàn)原理吧2023-03-03Python中實(shí)現(xiàn)限定抽獎(jiǎng)次數(shù)的機(jī)制的項(xiàng)目實(shí)踐
抽獎(jiǎng)系統(tǒng)作為吸引用戶、提高用戶參與度和活躍度的重要手段,本文主要介紹了Python中實(shí)現(xiàn)限定抽獎(jiǎng)次數(shù)的機(jī)制的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05解決Numpy報(bào)錯(cuò):ImportError: numpy.core.multiarray faile
這篇文章主要介紹了解決Numpy報(bào)錯(cuò):ImportError: numpy.core.multiarray failed問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01OpenCV中resize函數(shù)插值算法的實(shí)現(xiàn)過程(五種)
最新版OpenCV2.4.7中,cv::resize函數(shù)有五種插值算法:最近鄰、雙線性、雙三次、基于像素區(qū)域關(guān)系、蘭索斯插值。感興趣的可以了解一下2021-06-06