python实现多线程的两种方式

yipeiwu_com5年前Python基础

目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。
2.7版本之前python对线程的支持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading  模块。threading模块里面主要是对一些线程的操作对象化,创建Thread的class。一般来说,使用线程有两种模式:

A 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
B 继承Thread类,创建一个新的class,将要执行的代码 写到run函数里面。

本文介绍两种实现方法。
第一种 创建函数并且传入Thread 对象中
t.py 脚本内容

import threading,time
from time import sleep, ctime
def now() :
  return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
  print 'start loop', nloop, 'at:', now()
sleep(nsec)
  print 'loop', nloop, 'done at:', now()
def main():
  print 'starting at:',now()
  threadpool=[]
for i in xrange(10):
    th = threading.Thread(target= test,args= (i,2))
    threadpool.append(th)
for th in threadpool:
    th.start()
for th in threadpool :
    threading.Thread.join( th )
  print 'all Done at:', now()
if __name__ == '__main__':
    main()

 thclass.py 脚本内容:

import threading ,time
from time import sleep, ctime
def now() :
  return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
class myThread (threading.Thread) :
"""docstring for myThread"""
   def __init__(self, nloop, nsec) :
     super(myThread, self).__init__()
     self.nloop = nloop
     self.nsec = nsec
   def run(self):
     print 'start loop', self.nloop, 'at:', ctime()
sleep(self.nsec)
     print 'loop', self.nloop, 'done at:', ctime()
def main():
   thpool=[]
   print 'starting at:',now()
for i in xrange(10):
     thpool.append(myThread(i,2))
for th in thpool:
     th.start()
for th in thpool:
     th.join()
   print 'all Done at:', now()
if __name__ == '__main__':
    main()

以上就是本文的全部内容吗,希望对大家学习python程序设计有所帮助。

相关文章

python2.7实现邮件发送功能

python2.7实现邮件发送功能

要想实现一个能够发送带有文本、图片、附件的python程序,首先要熟悉两大模块: email以及smtplib 然后对于MIME(邮件扩展)要有一定认知,因为有了扩展才能发送附件以及...

python统计一个文本中重复行数的方法

本文实例讲述了python统计一个文本中重复行数的方法。分享给大家供大家参考。具体实现方法如下: 比如有下面一个文件 2 3 1 2 我们期望得到 2,2 3,1 1,1 解决问题的思路...

matplotlib subplots 设置总图的标题方法

如下所示: matplotlib subplots 设置总图的标题 : fig.suptitle(dname,fontsize=16,x=0.53,y=1.05,) 以上这篇matplo...

Python读写文件模式和文件对象方法实例详解

Python读写文件模式和文件对象方法实例详解

本文实例讲述了Python读写文件模式和文件对象方法。分享给大家供大家参考,具体如下: 一. 读写文件模式 利用open() 读写文件时,将会返回一个 file 对象,其基本语法格式如...

在Python中字典根据多项规则排序的方法

我们做登录的时候经常会使用到,验证手机号是否正确、向手机发送验证码倒计时60s的问题,我们改如何解决呢?让我们一起来探讨一下吧。如下图: 首先,我们先说说判断手机号码是否正确的问题吧...