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("结束")
阅读全文
0 0
- Python 多线层协调应用举例
- Python 正则表达式高级应用举例
- 神经网络算法应用举例【Python实现】
- 多元线性回归和Python应用举例
- 逻辑回归和Python应用举例
- python中event事件应用举例
- python驱动DDT框架应用--实战举例
- Android应用协调器------Intent
- Android应用协调器------Intent
- Android应用协调器------Intent
- Python 之metaclass应用举例 - xml to class
- python字符串应用举例:判断是否满足标题格式
- Android应用协调器------Intent[转]
- Android应用协调器------Intent (转载)
- 分布式协调服务ZooKeeper的典型应用
- 聚类算法之Kmean算法应用和Python应用举例
- Python多线程编程,线程之间的协调
- 使用 Python 进行分布式系统协调
- 选择排序、快速排序、冒泡排序、插入排序
- 如何选择compileSdkVersion, minSdkVersion 和 targetSdkVersion
- CSS3 background-size 属性
- Hibernate初学者---关于annotation注解的相关知识
- 【JAVA300】51-55 笔记
- Python 多线层协调应用举例
- Python实现KNN算法
- Linux C/C++程序员 但行好事 莫问前程 Linux系统下 解决Qt5无法连接MySQL数据库的方法
- hihocoder#1312 : 搜索三·启发式搜索(bfs+hash判重)
- 新浪微博帐号出售
- Get the temperature of Omni-Path ASIC
- 关于sessionStorage与localStorage的使用场景区别
- Lua_高级特性_014
- Python连接DB2数据库基本