Python 多线层协调应用举例

来源:互联网 发布:linux如何修改用户组 编辑:程序博客网 时间:2024/06/07 00:37

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("结束")

  

原创粉丝点击