频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

Python线程编程的两种方式

来源: 作者: 出处:巧巧读书 2006-05-22 进入讨论组

??? Python中如果要使用线程的话,python的lib中提供了两种方式。一种是函数式,一种是用类来包装的线程对象。举两个简单的例子希望起到抛砖引玉的作用,关于多线程编程的其他知识例如互斥、信号量、临界区等请参考python的文档及相关资料。

??? 1、调用thread模块中的start_new_thread()函数来产生新的线程,请看代码:

###?? thread_example.py
import time
import thread
def timer(no,interval):??????????????????????????????????????????????????????????? #自己写的线程函数
??? while True:
??????? print 'Thread :(%d) Time:%s'%(no,time.ctime())
??????? time.sleep(interval)
def test():
??? thread.start_new_thread(timer,(1,1))???????????????????????????????? #使用thread.start_new_thread()来产生2个新的线程
??? thread.start_new_thread(timer,(2,3))
if __name__=='__main__':
??? test()

这个是
thread.start_new_thread(function,args[,kwargs])
函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。
线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。

??? 2、通过调用threading模块继承threading.Thread类来包装一个线程对象。请看代码

### threading_example.py
import threading
import time
class timer(threading.Thread):???????????????????????????????????????? #我的timer类继承自threading.Thread类
??? def __init__(self,no,interval):
??????? threading.Thread.__init__(self)?????????????????????????????? #在我重写__init__方法的时候要记得调用基类的__init__方法
??????? self.no=no
??????? self.interval=interval
??? def run(self):?????????????????????????????????????????????????????????????? #重写run()方法,把自己的线程函数的代码放到这里
??????? while True:
??????????? print 'Thread Object (%d), Time:%s'%(self.no,time.ctime())
??????????? time.sleep(self.interval)
def test():
??? threadone=timer(1,1)???????????????????????????????????????????????? #产生2个线程对象
??? threadtwo=timer(2,3)
??? threadone.start()??????????????????????????????????????????????????????? #通过调用线程对象的.start()方法来激活线程
??? threadtwo.start()
if __name__=='__main__':
??? test()

其实thread和threading的模块中还包含了其他的很多关于多线程编程的东西,例如锁、定时器、获得激活线程列表等等,请大家仔细参考python的文档!

本文:http://www.qqread.com/itlife/c067113021.html 更多文章 更多内容请看Python实用指南Java编程开发手册Python相关文章专题,或进入讨论组讨论。
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章