两种Python线程编程方式简介

开发 后端
本文详细介绍Python线程编程的相关文章,因为目前大部分的脚本都不能提供如VC++那样方便的调试环境,希望大家能够学习介绍。

由于Python线程编程的DEMO太多,此处无法上传,所以大家有communitysever的可以从里面获得然后反编译为自己所用,没有的就到网络上搜下吧,有许多资源呢,仅供大家学习思考。

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

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

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

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

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

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

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

【编辑推荐】

  1. 如何使Python嵌入C++应用程序?
  2. 深入探讨Ruby与Python语法比较
  3. Python学习资料介绍分享
  4. Python学习经验谈:版本、IDE选择及编码解决方案
  5. 浅析Python的GIL和线程安全
责任编辑:chenqingxiang 来源: 计世网
相关推荐

2011-07-01 17:50:13

Python 多线程

2010-07-14 10:30:26

Perl多线程

2010-07-13 14:54:15

Perl面向对象编程

2011-03-03 10:26:04

Pureftpd

2010-04-28 16:23:18

Oracle数据库

2010-09-07 11:09:59

2010-08-06 09:38:11

Flex读取XML

2010-04-20 15:32:20

主控负载均衡

2009-06-23 18:18:13

SpringHibernate

2023-03-29 13:06:36

2010-03-11 14:34:47

Python环境

2009-06-25 13:43:00

Buffalo AJA

2021-05-27 10:57:01

TCP定时器网络协议

2010-10-21 16:24:18

sql server升

2010-03-18 10:18:52

python模块

2009-09-08 15:22:20

Spring依赖注入

2011-04-02 09:48:38

深拷贝

2010-07-15 14:38:55

Perl eval函数

2016-11-07 09:02:02

Malloc内存syscall

2011-06-16 10:02:08

JAVA静态载入
点赞
收藏

51CTO技术栈公众号