这几天学习人脸识别的时候,虽然运行的没有问题,但我却意识到了一个问题
在图片进行传输的时候,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()
总结