使用Condition对象实现线程同步,模拟生产者与消费者问题。

使用列表模拟物品池,生产者往里放置东西,而消费者从池中获取物品。物品池满时生产者等待,空时消费者等待。假设物品池里面能够容纳5个元素,每个元素都是1-1000之间的整数。请编写代码实现并查看运行结果。

import threading
from random import randint
from time import sleep
class producer(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global x
        while True:
            sleep(1)
            con.acquire()
            if len(x)==5:
                print('生产者等待....')
                con.wait()
            else:
                r=randint(1,1000)
                print('producer:',r)
                x.append(r)
                con.notify()
            con.release()
class consumer(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)
    def run(self):
        global x
        while True:
            sleep(3)
            con.acquire()
            if not x:
                print('消费者等待....')
                con.wait()
            else:
                print('consumer:',x.pop(0))
                con.notify()
            con.release()
con=threading.Condition()
x=[]
p=producer('producer')
c=consumer('consumer')
p.start()
c.start()

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/tcbdbd/article/details/85275236