Python线程编程的两种方式

Posted in Python by neemem on 08-21-2008.
loading
0
Digg me

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

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

python 代码
  1. ###        thread_example.py
  2. time
  3. thread
  4. def timer(no,interval): #自己写的线程函数
  5. while True:
  6. print ‘Thread :(%d) Time:%s’%(no,time.ctime())
  7. time.(interval)
  8. def test(): #使用thread.start_new_thread()来产生2个新的线程
  9. thread.start_new_thread(timer,(1,1))
  10. thread.start_new_thread(timer,(2,3))
  11. if __name__==’__main__‘:
  12. test()

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

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

python 代码
  1. time
  2. class timer(.Thread): #我的timer类继承自.Thread类
  3. def __init__(self,no,interval):
  4. #在我重写__init__方法的时候要记得调用基类的__init__方法
  5. .Thread.__init__(self)
  6. self.no=no
  7. self.interval=interval
  8. def run(self): #重写run()方法,把自己的线程函数的代码放到这里
  9. while True:
  10. print ‘Thread Object (%d), Time:%s’%(self.no,time.ctime())
  11. time.(self.interval)
  12. def test():
  13. threadone=timer(1,1) #产生2个线程对象
  14. threadtwo=timer(2,3)
  15. threadone.start() #通过调用线程对象的.start()方法来激活线程
  16. threadtwo.start()
  17. if __name__==’__main__‘:
  18. test()

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

Tags: , , , , , , ,

Related posts

输入“SB 饭桶 输人输球 浪费粮食 国猪”惊喜发现 PGSQL支持plPHP,phper有福了

Leave a Reply

Comment moderation is enabled. Your comment may take some time to appear.