Python线程的编程方式

发布时间:2021-08-25 15:09:00 作者:chen
来源:亿速云 阅读:103

这篇文章主要讲解了“Python线程的编程方式”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“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线程的编程方式”的内容了,经过本文的学习后,相信大家对Python线程的编程方式这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 并发编程专题(二)-线程的创建方式
  2. 线程调用方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python中变量的说明介绍

下一篇:Python静态编译器的用法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》