您的位置:首页 > 编程语言 > Python开发

[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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息