1. 程式人生 > 其它 >併發程式設計四(1) 執行緒同步 - 佇列

併發程式設計四(1) 執行緒同步 - 佇列

執行緒同步

控制執行緒執行順序

生產者與消費者,通過佇列實現同步(順序)

可以看下列印,是相對有序的

from queue import Queue # 佇列類
import random
import threading
import time

# 生產者執行緒
class Producer(threading.Thread):
    def __init__(self,t_name,queue):
        # 呼叫父執行緒的構造方法。
        threading.Thread.__init__(self,name=t_name)
        self.data=queue

    def run(self):
        for i in range(5):
            print("%s: %s is producing %d to the queue!\n" %(time.ctime(),self.getName(),i))
            self.data.put(i)  # 向佇列中新增資料
            # 產生一個0-2之間的隨機數進行睡眠
            time.sleep(random.randrange(10)/5)
        print("%s: %s finished!" %(time.ctime(),self.getName()))

# 消費者執行緒
class Consumer(threading.Thread):
    def __init__(self,t_name,queue):
        threading.Thread.__init__(self,name=t_name)
        self.data=queue

    def run(self):
        for i in range(6):
            val=self.data.get()   # 佇列中取出資料
            print("%s: %s is consuming. %d in the queue is consumed!\n" %(time.ctime(),self.getName(),val))
            time.sleep(random.randrange(10))
        print("%s: %s finished!" %(time.ctime(),self.getName()))

# Main thread
def main():
    queue=Queue()  # 建立一個佇列物件(先進先出)
    producer=Producer('Pro.',queue)  # 生產者物件
    consumer=Consumer('Con.',queue)  # 消費者物件
    producer.start()
    consumer.start()
    producer.join()
    consumer.join()
    print("All threads terminate.")

if __name__=="__main__":
    main()