1. 程式人生 > >使用Condition物件實現執行緒同步,模擬生產者與消費者問題。

使用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()

執行結果:
在這裡插入圖片描述