python 多線層協調應用舉例

1. threading.Event 機制應用

2. threading.Lock 防止子線層打印出錯

3. 再次遇到在python2.7中,中文字符串做爲形參傳遞時出現的問題並解決。

# coding:utf-8
from __future__ import unicode_literals
import threading
import time

# " 媽媽作飯,我弟吃,我刷碗 "
# 用事件(Event)對象實現進程時間順序上的調度
# python2.7 字符串做爲實參傳遞時,彷佛必需要用 utf-8 格式編碼,爲了跟python 3 儘可能保持同步 
# from __future__ import unicode_literals,即字符串常量默認爲 unicode 編碼,
# 字符串之間進行運算時也要轉換爲一樣的編碼格式,因此utf-8格式參數要解碼(decode)

food_prepared = threading.Event()
food_finished = threading.Event()
finished = threading.Event()
print_lock = threading.Lock()

# 爲了防止多個線程在控制檯打印時出現衝突,對打印行爲加鎖
def safe_print(string):
    print_lock.acquire()
    print(string)
    print_lock.release()

class bro (threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def finish_food(self):
        safe_print("弟弟吃完了")
    def run(self):
        if food_prepared.wait(20):
            safe_print("弟弟在吃飯")
            time.sleep(3)
            self.finish_food()
            food_finished.set()
        else:
            safe_print("弟弟等不及出去吃了")


class mother(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        safe_print(self.name.decode("utf-8") + "在作飯")
        time.sleep(5)
        food_prepared.set()
        

class me(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def do_dish(self):
        safe_print(self.name.decode("utf-8") + "在刷碗")
        time.sleep(3)
        safe_print("刷完了")
    def run(self):
        food_prepared.wait()
        safe_print(self.name.decode("utf-8") + "等着刷碗")
        food_finished.wait(20)
        safe_print("弟弟吃完了我來刷碗")
        self.do_dish()
        finished.set()

a = me("我".encode("utf-8"))
b = bro("弟弟".encode("utf-8"))
c = mother("媽媽".encode("utf-8"))
c.start()
a.start()
b.start()
finished.wait()
safe_print("結束")
相關文章
相關標籤/搜索