python queue threading_Python多线程:thread、threading、queue | 学步园

一、名字解释

Python虚拟机:也叫解释器主循环,控制Python代码的执行。

多线程:类似单CPU系统中运行多个进程。 任意时刻,只能有一个线程在解释器中运行。

全局解释器锁(GIL):保证同一个时刻只有一个线程在运行。

二、thread

#!/usr/bin/env python

#import thread

from time import sleep, ctime

def loop0():

print "start loop 0 at:", ctime()

sleep(4)

print "end loop 0 at:", ctime()

def loop1():

print "start loop 1 at:", ctime()

sleep(2)

print "end loop 1 at:",ctime()

def main():

print "starting at:", ctime()

loop0()

loop1()

#thread.start_new_thread(loop0,())

#thread.start_new_thread(loop1,())

#sleep(6)

print "ending at:", ctime();

if __name__ == "__main__":

main()

没有thread:共耗时4+2=6秒

有thread,无锁:并发执行,共耗时4秒,需要主线程中手动sleep

#!/usr/bin/env python

import thread

from time import sleep, ctime

secs = [4,2]

def loop(nloop, nsec, lock):

print "start loop ", nloop," at:", ctime()

sleep(nsec)

print "end loop ", nloop, " at:", ctime()

lock.release()

def main():

print "starting at:", ctime()

nsecs = range(len(secs))

locks = []

for i in nsecs:

lock = thread.allocate_lock()

lock.acquire()

locks.append(lock)

for i in nsecs:

thread.start_new_thread(loop, (i, secs[i], locks[i]))

for i in nsecs:

while locks[i].locked(): pass

print "ending at:", ctime();

if __name__ == "__main__":

main()

有thread,有锁:共耗时4秒,主线程无需等待

三、threading

3种创建线程方法

1. 创建一个Thread的实例,传给它一个函数

2. 创建一个Thread的实例,传给它一个可调用的类对象

3. 从Thread派生出一个子类,创建一个这个子类的实例

#!/usr/bin/env python

import threading

from time import sleep, ctime

secs = [4,2]

#class ThreadFunc(object):

# def __init__(self, func, args, name=''):

# self.name = name

# self.func = func

# self.args = args

#

# def __call__(self):

# apply(self.func, self.args)

def loop(nloop, nsec):

print "start loop ", nloop, " at:", ctime()

sleep(nsec)

print "end loop ", nloop," at:", ctime()

def main():

print "starting at:", ctime()

nsecs = range(len(secs))

threads = []

for i in nsecs:

#t = threading.Thread(target=ThreadFunc(loop, (i, secs[i]), loop.__name__))

t = threading.Thread(target=loop,args=(i,secs[i]))

threads.append(t)

for i in nsecs:

threads[i].start()

for i in nsecs:

threads[i].join()

print "ending at:", ctime();

if __name__ == "__main__":

main()

上述代码是2种创建线程方法:执行结果一样,都是耗时4秒,主线程无需等待

      

四、尽量使用threading,避免使用thread

1. threading模块更为先进,对线程支持更完善,使用thread模块可能会与threading出现冲突。

2. thread模块同步原语少(只有一个),threading模块有很多。

3. thread,当主线程结束时,所有线程都被强制结束掉;threading模块能确保重要的子线程退出口进程再退出。

五、Queue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值