python 使用多線程創建一個Buffer緩存器的實現思路
這幾天學習人臉識別的時候,雖然運行的沒有問題,但我卻意識到了一個問題
在圖片進行傳輸的時候,GPU的利用率為0
也就是說,圖片的傳輸速度和GPU的處理速度不能很好銜接
于是,我打算利用多線程開發一個buffer緩存
實現的思路如下
定義一個Buffer類,再其構造函數中創建一個buffer空間(這里最好使用list類型)
我們還需要的定義線程鎖LOCK(數據傳輸和提取的時候會用到)
因為需要兩種方法(讀數據和取數據),所以我們需要定義兩個鎖
實現的代碼如下:
#-*-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 使用多線程創建一個Buffer緩存器的文章就介紹到這了,更多相關python 多線程Buffer緩存器內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )2. 在JSP中使用formatNumber控制要顯示的小數位數方法3. MyBatis JdbcType 與Oracle、MySql數據類型對應關系說明4. jsp網頁實現貪吃蛇小游戲5. django創建css文件夾的具體方法6. 利用CSS制作3D動畫7. ASP中if語句、select 、while循環的使用方法8. .NET SkiaSharp 生成二維碼驗證碼及指定區域截取方法實現9. 存儲于xml中需要的HTML轉義代碼10. ASP中實現字符部位類似.NET里String對象的PadLeft和PadRight函數
