python实现多线程的常见方式

目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。

一般来说,使用线程有两种模式:

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

t.py 脚本内容

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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 脚本内容:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值