调整一下,也能实现交替操作
[Python] 纯文本查看 复制代码 from multiprocessing import Process, Semaphore, Lock, Queue
import time
from random import random
def consumer(buffer, lock, empty, full):
# while not buffer.empty():
while True:
full.acquire()
lock.acquire()
print(f'Consumer get {buffer.get()}')
time.sleep(1)
lock.release()
empty.release()
def producer(buffer, lock, empty, full):
while True:
empty.acquire()
lock.acquire()
num = random()
print(f'Producer append an {num}')
buffer.put(num)
time.sleep(1)
lock.release()
full.release()
if __name__ == '__main__':
buffer = Queue(10)
empty = Semaphore(2)
full = Semaphore(0)
lock = Lock()
p = Process(target=producer, args=(buffer, lock, empty, full))
c = Process(target=consumer, args=(buffer, lock, empty, full))
p.daemon = True
c.daemon = True
p.start()
c.start()
p.join()
c.join()
print('Ended!')
|