[Python]多线程入门 --thread使用
2013-04-01 17:57
525 查看
多线程编程的使用场景:
任务本质上是异步的,需要有多个并发事务,各个事务的运行顺序可以是不确定的,随机的,不可预测的。这样的编程任务可以被分成多个执行流,每个流都有一个要完成的目标。 进程:程序以一次执行。 线程:所有的线程运行在同一个进程中,共享相同的运行环境。 python 解释器中可以运行多个“线程”,但在任意时刻,只有一个线程在解释器中运行。 python 虚拟机执行方式:1 设置GIL2切换到一个线程中去运行3 运行: a. 指定数量的字节码指令,或者 b. 线程主动让出控制4 把线程设置为睡眠状态5 解锁GIL6
再次重复以上所有步骤
常用的多线程模块:thread threading Queue 不推荐使用的是thread模块,另一个不使用thread的原因是它不支持守护线程。
使用thread的案例2个
#!/usr/bin/env python import thread from time import sleep,ctime def loop0(): print 'the loop 0 start: ',ctime() sleep(6) print 'loop 0 is end: ',ctime() def loop1(): print 'the loop 1 start: ',ctime() sleep(4) print 'loop 1 is end: ',ctime() def main(): print 'the main is start: ',ctime() thread.start_new_thread(loop0,()) thread.start_new_thread(loop1,()) sleep(10) #为什么会有这一段代码呢,要是没有它就会怎么样呢 (没有线程同步) print 'main thread is end: ',ctime() if __name__=='__main__': main()
使用线程锁
#!/usr/bin/env python import thread from time import sleep,ctime def loop0(): print 'the loop 0 start: ',ctime() sleep(6) print 'loop 0 is end: ',ctime() def loop1(): print 'the loop 1 start: ',ctime() sleep(4) print 'loop 1 is end: ',ctime() def main(): print 'the main is start: ',ctime() thread.start_new_thread(loop0,()) thread.start_new_thread(loop1,()) sleep(10) print 'main thread is end: ',ctime() if __name__=='__main__': main()
线程同步,守护线程的知识不是很明了,还学要找点资料补习下。
本文出自 “orangleliu笔记本” 博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/8747737
相关文章推荐
- 【python标准库学习】thread,threading(一)多线程的介绍和使用
- python多线程(2)--thread和threading模块的使用
- 多线程在python中的使用 thread
- python之潜心研究多线程(thread模块) 建议使用threading模块
- Python多线程 - 使用_thread模块实现多线程
- python 多线程 thread 不推荐使用(一)
- python多线程使用thread
- 多线程在python中的使用 thread
- python 8-1 如何使用多线程,Thread创建线程,执行函数赋值给target//类+函数放在run方法中执行
- opencv 入门教程, ubuntu安装,及python 下简单使用
- Python模块学习 ---- thread 多线程处理
- iOS多线程编程之NSThread的使用
- python爬虫从入门到放弃(七)之 PyQuery库的使用
- python的nltk中文使用和学习资料汇总帮你入门提高
- python线程池(threadpool)模块使用
- iOS 多线程之NSThread简单使用
- Java中使用Thread创建多线程并启动
- python RabbitMQ队列使用(入门篇)
- Python多线程使用及线程同步
- python多进程与多线程使用场景