標籤:出錯 參數 字元 傳遞 編碼 sel 中文字串 start string
1. threading.Event 機制應用2. threading.Lock 防止子線層列印出錯3. 再次遇到在python2.7中,中文字串作為形參傳遞時出現的問題並解決。
# coding:utf-8from __future__ import unicode_literalsimport threadingimport 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("結束")
python 多線層協調應用舉例