python 多線層協調應用舉例

來源:互聯網
上載者:User

標籤:出錯   參數   字元   傳遞   編碼   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 多線層協調應用舉例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.