带有python 3.5的有界缓冲区(生产者/消费者)

时间:2016-03-14 18:15:36

标签: python asynchronous parallel-processing multiprocessing

我正在编写Python 3.5中的经典生产者/消费者问题,使用deque作为buff和2进程应该并行工作但不幸的是只有生产者工作,而消费者不“消费”..我在哪里错误?这是我的代码:

from time import sleep
import random
from collections import deque
import multiprocessing

MAX_LEN = 10
buff = deque(maxlen=MAX_LEN)

class producer:
    while True:
        if len(buff) == MAX_LEN:
            print("Producer: The buff is full, waiting...")
            sleep(10)
        buff.append(random.randint(1,9))


class consumer:
    while True:
        print("Consumer: hi")
        if len(buff) == 0:
            print("Consumer: The buff is empty, waiting...")
            sleep(10)
        buff.pop()



if __name__ == '__main__':
    multiprocessing.Process(target=producer).start().join()
    multiprocessing.Process(target=consumer).start().join()

,结果是:

Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
^CTraceback (most recent call last):
  File "./boundedbuffer.py", line 9, in <module>
    class producer:
  File "./boundedbuffer.py", line 13, in producer
    sleep(10)
KeyboardInterrupt

就目前而言,我想以这种方式实现,作为练习,只是为了看看我是否理解这个论点,虽然我知道它不是最正确的,我应该使用信号量或监视器。也许以后我会尝试以不同的方式实现它。 提前感谢大家的帮助和晚上好!:)

1 个答案:

答案 0 :(得分:1)

您已经在其正文中定义了//script for sliders var currentlyAnimating = false; $('.box-left').click(slideleft); $( ".r-wide-box" ).on( "swipeleft", slideleft); $('.box-right, .phone-next-serv').click(slideright); $( ".r-wide-box" ).on( "swiperight", slideright); function slideleft ( ){ var width = $(".wide-box > .row-fluid-wrapper").width(); if (currentlyAnimating) { return; } currentlyAnimating = true; $('.wide-box > .row-fluid-wrapper:last').prependTo('.wide-box'); $('.wide-box').css('left', -width); $('.wide-box').animate({ left: '0px' }, 500, 'linear', function() { $('.wide-box').css('left', '0px'); currentlyAnimating = false; }); } function slideright ( ){ var width = $(".wide-box > .row-fluid-wrapper").width(); if (currentlyAnimating) { return; } currentlyAnimating = true; $('.wide-box').animate({ left: -width }, 500, 'linear', function() { $('.wide-box').css('left', '0px'); $('.wide-box > .row-fluid-wrapper:first').appendTo('.wide-box'); currentlyAnimating = false; }); }; 个循环的类。

解释器将永久执行文件中的第一个while循环。

while True:期望一个callable作为其目标参数,因此如果您将生产者和消费者类更改为函数,multiprocessing.Process块将被执行(尽管您仍然可能无法得到您期望的结果)

if __ name __ == __ main __ :