python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。thread是比较底层的模 块,threading是对thread做了一些包装的,可以更加方便的被使用。这里需要提一下的是python对线程的支持还不够完善,不能利用多 CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧。
threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。一般来说,使用线程有两种模式,一种是创建线程要执行的 函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里
python对于thread的管理中有两个函数:join和setDaemon
join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的。
Queue模块允许创建指定长度的队列. 下面是Queue模块的常用方法:
get():删除并返回队列中的一个项目
put(): 添加项目到队列
qsize() : 返回队列中元素的个数
empty(): 队列为空返回True否则返回False
full(): 队列已满返回True,负责返回False
输出结果