使用线程从双端队列中弹出整数

时间:2019-12-16 10:48:13

标签: python multithreading

这四天我很累,但是仍然坚持 请帮助我解决该线程问题。

下一张幻灯片中的程序有2个线程,分别运行生产者和 消费者。他们通过双端队列进行通信。

•生产者将双精度数0,1、2,...和9写入双端队列。

•使用者尝试从双端队列中弹出整数以建立列表。但 列表中随机缺少数字。对于每个省略的数字, 是弹出的错误消息。

修改程序,以便不再有弹出错误 整数出现在输出列表中。

import time
import threading
import random
from collections import deque

def int_producer(n, d):
    for i in range(n):
        time.sleep(random.random()/10)
        d.append(i)

def int_consumer(n, d):
    my_list = []
    for i in range(n):
        time.sleep(random.random()/10)
        try:
            my_list.append(d.popleft())
        except IndexError:
            print("pop error")
    print(my_list)

def main():
    d = deque(maxlen=3)
    threads = [threading.Thread(daemon=True, target=int_producer,
                                args=(10,d)) for i in range(3)]
    threads.extend([threading.Thread(daemon=True, target=int_consumer,
                                    args=(10,d)) for i in range(3)])
    [thread.start() for thread in threads]
    [thread.join() for thread in threads]

if __name__ == '__main__':
    main()

这是我的代码

import time
import threading
import random
from collections import deque

def int_producer(n, d):
    global has_space, has_full 

    for i in range(n):
        time.sleep(random.random()/10)
        with has_full:
            while len(d) == 3 :
                print ( ' wait here ' )
                has_full.wait()
        with has_space:
            d.append(i)
            has_space.notify()


def int_consumer(n, d):
    global has_space, has_full 

    my_list = []
    for i in range(n):
        time.sleep(random.random()/10)
        try:
            with has_space:
                while len(d) == 0 :
                    has_space.wait()


            with has_full:
                while len(d) == 3 :
                    has_full.notify()


            my_list.append(d.popleft())    


        except IndexError:
            print("pop error")
    print(my_list)

def main():
    global cv, has_space, has_full 
    has_full = threading.Condition()
    has_space = threading.Condition()

    d = deque(maxlen=3)
    threads = [threading.Thread(daemon=True, target=int_producer,
                                args=(10,d)) for i in range(3)]
    threads.extend([threading.Thread(daemon=True, target=int_consumer,
                                    args=(10,d)) for i in range(3)])
    [thread.start() for thread in threads]
    [thread.join() for thread in threads]

if __name__ == '__main__':
    main()

结果就像,列表应该是[0,1,2,3,4,5,6,7,8,9]

[0, 0, 1, 3, 2, 3, 5, 6, 7, 7]
[2, 2, 3, 4, 5, 5, 6, 7, 8, 8]
[0, 1, 1, 4, 4, 6, 9, 8, 9, 9]

0 个答案:

没有答案