Python线程的两种编程方式
更新时间:2015年04月14日 10:44:36 投稿:junjie
这篇文章主要介绍了Python线程的两种编程方式,Python中如果要使用线程的话,一种是函数式,一种是用类来包装的线程对象,需要的朋友可以参考下
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()来产生2个新的线程
thread.start_new_thread(timer,(1,1))
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类来包装一个线程对象。请看代码:
复制代码 代码如下:
import threading
import time
class timer(threading.Thread): #我的timer类继承自threading.Thread类
def __init__(self,no,interval):
#在我重写__init__方法的时候要记得调用基类的__init__方法
threading.Thread.__init__(self)
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的文档!
相关文章
Python中类方法@classmethod和静态方法@staticmethod解析
这篇文章主要介绍了Python中类方法@classmethod和静态方法@staticmethod解析,python中存在三种方法,分别为常规方法(定义中传入self)、@classmethod修饰的类方法、@staticmethod修饰的静态方法,,需要的朋友可以参考下2023-08-08Windows平台Python连接sqlite3数据库的方法分析
这篇文章主要介绍了Windows平台Python连接sqlite3数据库的方法,结合实例形式分析了Windows平台安装SQLite数据库及创建、连接数据库的实现方法与相关注意事项,需要的朋友可以参考下2017-07-07详解使用Pytorch Geometric实现GraphSAGE模型
这篇文章主要为大家介绍了详解使用Pytorch Geometric实现GraphSAGE模型示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04pycharm中报ModuleNotFoundError:No module named 'tensor
这篇文章主要给大家介绍了关于pycharm中报ModuleNotFoundError:No module named 'tensorflow'错误的解决方法,文中通过图文介绍的非常详细,需要的朋友可以参考下2023-07-07
最新评论