python实现多线程的两种方式

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python编程实现及时获取新邮件的方法示例

本文实例讲述了Python编程实现及时获取新邮件的方法。分享给大家供大家参考,具体如下: #-*- encoding: utf-8 -*- import sys import loc...

Python基础教程之内置函数locals()和globals()用法分析

本文实例讲述了Python基础教程之内置函数locals()和globals()用法。分享给大家供大家参考,具体如下: 1. 这两个函数主要提供,基于字典的访问局部变量和全局变量的方式。...

python进阶教程之异常处理

在项目开发中,异常处理是不可或缺的。异常处理帮助人们debug,通过更加丰富的信息,让人们更容易找到bug的所在。异常处理还可以提高程序的容错性。 我们之前在讲循环对象的时候,曾提到一个...

pyqt5的QComboBox 使用模板的具体方法

pyqt5的QComboBox 使用模板的具体方法

QComboBox 的常规使用方法,在这个使用模板里,基本都有了。 QComboBox小部件是一个组合的按钮和弹出列表。 QComboBox提供了一种向用户呈现选项列表的方式,其占用最小...

python实现根据用户输入从电影网站获取影片信息的方法

本文实例讲述了python实现根据用户输入从电影网站获取影片信息的方法。分享给大家供大家参考。具体如下: 这段python代码主要演示了用户终端输入,正则表达式,网页抓取等 #!/u...