【Python@Thread】threading模块

  theading模块的Thread类

属性:

    name   线程名

    ident   线程标识符

    daemon   布尔值,标示是否为守护线程

方法:

  __init__(target=None, name=None, *args=(), **kwargs={})

  start()   开始执行线程

  run()    定义线程功能的方法

  join(timeout=None)  阻塞线程,等待被唤醒,好于忙等待

Thread类的使用主要有三种方法:

1.创建Thread实例,传给其一个参数

2.创建Thread实例,传给其一个可调用的类实例

3.派生Thread子类,创建子类实例

下面介绍这三种用法:

1.创建Thread实例,传给其一个参数

 1 from threading import Thread
 2 from time import ctime, sleep
 3 
 4 loops = [4, 2]
 5 
 6 
 7 def loop(nloop, nsec):
 8     print('loops ', nloop, 'starting at:', ctime())
 9     sleep(nsec)
10     print('loop', nloop, 'end at:', ctime())
11 
12 
13 def main():
14     print('starting at:', ctime())
15     threads = []
16 
17     for i in range(len(loops)):
18         t = Thread(target=loop, args=(i,loops[i]))
19         threads.append(t)        ###保存类实例
20 
21     for i in range(len(loops)):
22         threads[i].start()        ###同时启动类实例
23 
24     for i in range(len(loops)):
25         threads[i].join()          ###保持主线程切出
26 
27     print('all done at:', ctime())
28 
29 if __name__ == '__main__':
30     main()

运行结果:

starting at: Mon Dec 19 23:29:58 2016
loops 0 starting at: Mon Dec 19 23:29:58 2016
loops 1 starting at: Mon Dec 19 23:29:58 2016
loop 1 end at: Mon Dec 19 23:30:00 2016
loop 0 end at: Mon Dec 19 23:30:02 2016
all done at: Mon Dec 19 23:30:02 2016

  方法1,传入函数创建类实例,不用人为设置锁,释放锁

方法二:传入可调用类创建类实例(用法感觉有点像装饰器)

 1 from threading import Thread
 2 from time import ctime, sleep
 3 
 4 loops = [4, 2]
 5 
 6 
 7 class TFun():
 8     def __init__(self, name, func, args):
 9         self.name = name
10         self.func = func
11         self.args = args
12 
13     def __call__(self):
14         return self.func(*self.args)
15 
16 
17 def loop(nloop, nsec):
18     print('loop ', nloop, 'at:', ctime())
19     sleep(nsec)
20     print('loop ', nloop, 'at:', ctime())
21 
22 
23 def main():
24     print('starting at:', ctime())
25     threads = []
26 
27     for i in range(len(loops)):
28         t = Thread(target=TFun(loop.__name__, loop, (i,loops[i])))
29         threads.append(t)
30 
31     for i in range(len(loops)):
32         threads[i].start()
33 
34     for i in range(len(loops)):
35         threads[i].join()
36 
37     print('all done at:', ctime())
38 
39 if __name__ == '__main__':
40     main()

运行结果:

starting at: Mon Dec 19 23:46:31 2016
loop 0 at: Mon Dec 19 23:46:31 2016
loop 1 at: Mon Dec 19 23:46:31 2016
loop 1 at: Mon Dec 19 23:46:33 2016
loop 0 at: Mon Dec 19 23:46:35 2016
all done at: Mon Dec 19 23:46:35 2016

方法三:

派生Thread子类,创建子类实例

 1 from threading import Thread
 2 from time import ctime, sleep
 3 
 4 loops = [4, 2]
 5 
 6 
 7 class mythread(Thread):
 8     def __init__(self, func, args, name=''):
 9         Thread.__init__(self)
10         self.name = name
11         self.func = func
12         self.args = args
13         self.name = name
14 
15     def run(self):          #注意不是__call__(self)
16         self.func(*self.args)
17 
18 
19 def loop(nloop, nsec):
20     print('loop', nloop, 'at:', ctime())
21     sleep(nsec)
22     print('loop ', nloop, 'end at:', ctime())
23 
24 
25 def main():
26     print('starting at:', ctime())
27     threads = []
28 
29     for i in range(len(loops)):
30         t = mythread(loop,(i,loops[i]))
31         threads.append(t)
32 
33     for i in range(len(loops)):
34         threads[i].start()
35 
36     for i in range(len(loops)):
37         threads[i].join()
38 
39     print('end at:', ctime())
40 
41 if __name__ == '__main__':
42     main()

运行结果:

starting at: Tue Dec 20 00:06:00 2016
loop 0 at: Tue Dec 20 00:06:00 2016
loop 1 at: Tue Dec 20 00:06:00 2016
loop 1 end at: Tue Dec 20 00:06:02 2016
loop 0 end at: Tue Dec 20 00:06:04 2016
end at: Tue Dec 20 00:06:04 2016

  方法二和方法三可以测试多个函数,其中方法三更加直观。但是方法1更加简单

 参考资料:Python核心编程.第四章.Wesley Chun著

posted @ 2016-12-20 00:09  wilderness  阅读(460)  评论(0编辑  收藏  举报