python——多线程thread
来源:互联网 发布:unetbootin启动linux 编辑:程序博客网 时间:2024/05/29 14:37
python通过thread模块支持多线程,语法也很简洁,现在通过一个实例来看一下python中的多线程:
import threadimport time#保证只额外启动一个线程isRunning=False#启动的时间控制,测试时间是23点44分,所以定的是这个时间,可以用于指定定时任务的执行时间timer_hour=23timer_min=44#额外其他一个线程处理任务def another_thread(): print '[another_thread] is start...' #声明使用全局变量isRunning global isRunning #for循环模拟任务执行 for i in range(3): time.sleep(1) print '[another_thread] time: %s ' % time.strftime('%Y-%m-%d %X',time.localtime()) print '[another_thread] Is Running: %s' % isRunning #此处只是为了保证该任务一天只启动一次,一分不会超过60秒 time.sleep(60) print '[another_thread] is end...' #该状态只是为了保证该任务不会重复启动,当然对于任务可以设置一个超时时间,到时不结束自动终结 isRunning = Falseif __name__ == '__main__': while True: now = time.localtime() print '[main_thread] time: %s' % time.strftime('%Y-%m-%d %X',now) print '[main_thread] Is Running: %s' % isRunning if now.tm_hour==timer_hour and now.tm_min==timer_min and not isRunning: #进入任务前即置为True状态,防止重复启动 isRunning = True #python开启一个新的线程,从后面打印日志的情况可以知道,并不会影响主线程的运行 thread.start_new_thread(another_thread,()) time.sleep(1)
代码执行后如下:
C:\Users\Captain\Desktop>python task.py[main_thread] time: 2013-07-31 23:44:56[main_thread] Is Running: False[another_thread] is start...[main_thread] time: 2013-07-31 23:44:57[another_thread] time: 2013-07-31 23:44:57[main_thread] Is Running: True[another_thread] Is Running: True[main_thread] time: 2013-07-31 23:44:58[another_thread] time: 2013-07-31 23:44:58[main_thread] Is Running: True[another_thread] Is Running: True[main_thread] time: 2013-07-31 23:44:59[another_thread] time: 2013-07-31 23:44:59[another_thread] Is Running: True[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:00[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:01[main_thread] Is Running: True[main_thread] time: 2013-07-31 23:45:02
该实例很简单,可按照这个思路,应用于定时任务,心跳检测,守护进程等实际场景中
- python——多线程thread
- Javase—Thread多线程
- thread/threading/Queue/mutex——Python 多线程
- Python 多线程编程,thread
- python多线程thread
- Python thread 多线程
- python多线程模块thread
- Python 多线程 Thread包
- Python 多线程 thread
- python--thread多线程总结
- Python多线程(Thread)
- 多线程5——Thread
- Java多线程——Thread
- JAVA——多线程Thread
- C#Thread类—多线程
- java—多线程编程 Thread
- [Python]多线程入门 --thread使用
- Python:继承Thread实现多线程
- HDU 1728 BFS
- VLC测试RTSP请求,附RTSP交互流程
- CListCtrl使用技巧
- mysql 如何实现oracle中decode(...)函数的功能
- 最新版ffmpeg源码分析一:框架
- python——多线程thread
- CListCtrl一行显示多个图标问题
- ffmpeg源码学习
- concat()函数引发的思考
- 使用dd命令快速生成大文件或者小文件的方法
- 使用POI导出excel
- 漫谈android开发之菜单(一)
- flex提示安全沙箱
- 哈佛为什么群星闪耀?