码迷,mamicode.com
首页 > 编程语言 > 详细

Python多线程实现方法有几种

时间:2016-05-30 16:38:17      阅读:456      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
麦子学院
加入时间:2015-07-08
  关注此人  发短消息
文章分类
麦子学院”关注的人------(0
麦子学院”的粉丝们------(0
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!