[错误]: 当折叠/展开时,长的代码块可能会重叠或显示混乱的内容
import threading, time from collections import deque class BoundedBuffer: # This class is a thread def init(self, n): self.buf = deque() # Shared data: only accessible through put/get self.n = n self.lock = threading.Lock() # The entry lock of the thread self.not_full = threading.Condition(self.lock) # Condition variable: the buffer is not full self.not_empty = threading.Condition(self.lock) # Condition variable: the buffer is not empty def put(self, item): with self.lock: # Enter the thread (others are in it, so wait at this line) while len(self.buf) == self.n: self.not_full.wait() # Full: temporarily leave the thread to wait, let others enter self.buf.append(item) print(f"Produced {item}, buffer: {list(self.buf)}") self.not_empty.notify() # Wake up a thread waiting for "not empty" # Exit the with block = leave the thread
内容来源: CherryHQ/cherry-studio