Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

输出两行便卡住了,但是在原书的输出是完整的多行内容,多次确认过代码后发现代码无误但是输出内容与原文不同。望大佬解答十分感谢

import time
from multiprocessing import Lock, Process, Queue, Semaphore
from random import random

buffer = Queue(10)
empty = Semaphore(2)
full = Semaphore(0)
lock = Lock()

class Consumer(Process):

def run(self):
    global buffer, empty, full, lock
    while True:
        full.acquire()
        lock.acquire()
        print(f'Consumer get {buffer.get()}')
        time.sleep(1)
        lock.release()
        empty.release()

class Producer(Process):

def run(self):
    global buffer, empty, full, lock
    while True:
        empty.acquire()
        lock.acquire()
        num = random()
        print(f'Producer put {num}')
        buffer.put(num)
        time.sleep(1)
        lock.release()
        full.release()

if name == '__main__':

p = Producer()
c = Consumer()
p.daemon = True
c.daemon = True
p.start()
c.start()
p.join()
c.join()
print('Main Process Ended')

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...