欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 使用多線程創(chuàng)建一個(gè)Buffer緩存器的實(shí)現(xiàn)思路

 更新時(shí)間:2020年07月02日 09:49:31   作者:繁華落盡、時(shí)光靜好  
這篇文章主要介紹了python 使用多線程創(chuàng)建一個(gè)Buffer緩存器的實(shí)現(xiàn)思路,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

這幾天學(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)文章

最新評論