Python多线程机制初探.doc
文本预览下载声明
Python多线程机制初探
摘要:该文初步探讨了phthon多线程应用的两种方式:_thread模块和threading模块,两种实现途径各有优点和缺点,_thread模块是phthon的低级方式,接口更加直接和灵活;threading模块是thread的二次封装,使用起来更加方便,具体应用要根据实际情况灵活选择。
关键词:多线程;机制;初步探讨
中图分类号:TP311文献标识码:A文章编号:1009-3044(2011)19-4739-02
Mechanism of Multi-threaded Python
XIE Hong
(Core and File Administrative Offices, Exploration and Development Institute of Jidong Oilfield, Tangshan 063000, China)
Abstract: This paper discussed a multi-threaded applications phthon two ways: _thread module and the threading module, both ways have advantages and disadvantages to achieve, _thread phthon low-levelmodule is the way, the interface is more direct and flexible; threadingmodule is the thread of Secondary package is more convenient to use, the specific application the flexibility to choose according to the actual situation.
Key words: multi-threaded; mechanism; preliminary study
1 综述
当我们上网观看视频时,我们不希望等很长时间当视频全部下载完成再观看,又比如当开发需要支持大量客户机的服务器的应用程序时,我们希望服务器“并发地”连接许多客户端,从而缩短用户(客户端)响应时间,这个时候使用线程就是十分必要的了。实际上象迅雷、网际快车,在线视频播放工具等已经在自己软件中实现了“线程”、“并发”。
如何使用线程?Python标准库中有两个模块_thread和threading来提供对线程的支持。其中_thread模块使用较初级的方式使用和控制线程,但它有较大的编程灵活性。而threading模块通过对thread进行二次封装,提供了更方便的应用程序接口来处理线程。
下面让我们看看_thread和threading是怎么进行多线程编程的。
2 _thread模块中的线程:
关于_thread模块中线程的运用,先看一个例子:
#!/user/bin/python
# -*- coding: gb18030 -*-
# _*_ coding:UTF-8 _*_
import _thread
import time
import random
count = 0
lock = _thread.allocate_lock()
def threadAdd():
global count,lock
lock.acquire()
for i in range(500):
count += 1
lock.release()
for i in range(10):
_thread.start_new_thread(threadAdd, ())
time.sleep(2)
print (count)
这里介绍一下关键代码:
①import _thread 是导入_thread线程模块以便使用python的thread功能;
②lock = _thread.allocate_lock() 是创建一个锁,以便保证线程之间的正常通信,从而保证计算的正确性;
③def threadAdd() 函数定义了一个实现count 自增1的主函数;
④lock.release() 语句释放锁以便其它线程可以使用本线程的数据;
⑤for i in range(10):
_thread.start_new_thread(threadAdd, ())
循环语句启动10个线程,每个线程进行一次count自增1的
显示全部