@linux1s1s
2017-08-09T18:49:35.000000Z
字数 1953
阅读 1259
Python
2017-08
这里简要记录
Python核心编程
读书笔记 整段代码 可以直接运行
# -*- coding:gb18030 -*-
# 线程同步 Threading + 简单类封装
import threading
from time import sleep, ctime
loops = [2, 2]
class ThreadFunc(object):
def __init__(self, func, args, name=''):
self.func = func
self.args = args
self.name = name
def __call__(self, *args, **kwargs):
apply(self.func, self.args)
def loop(nloop, during):
print 'Lopper ', nloop, 'start at: ', ctime()
sleep(during)
print 'Lopper ', nloop, 'stop at: ', ctime()
def main():
print 'Lopper start at: ', ctime()
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print 'Lopper stop at: ', ctime()
if __name__ == '__main__':
main()
C:\Python27\python.exe H:/workspace/python-hw/hw-7.py
Lopper start at: Wed Aug 09 18:44:41 2017
Lopper 0 start at: Wed Aug 09 18:44:41 2017
Lopper 1 start at: Wed Aug 09 18:44:41 2017
Lopper 1 stop at: Wed Aug 09 18:44:43 2017
Lopper 0 stop at: Wed Aug 09 18:44:43 2017
Lopper stop at: Wed Aug 09 18:44:43 2017
Process finished with exit code 0
我们将上面代码中L36-40 合并在一个遍历中,其他不变
for i in nloops:
threads[i].start()
threads[i].join()
C:\Python27\python.exe H:/workspace/python-hw/hw-7.py
Lopper start at: Wed Aug 09 18:46:05 2017
Lopper 0 start at: Wed Aug 09 18:46:05 2017
Lopper 0 stop at: Wed Aug 09 18:46:07 2017
Lopper 1 start at: Wed Aug 09 18:46:07 2017
Lopper 1 stop at: Wed Aug 09 18:46:09 2017
Lopper stop at: Wed Aug 09 18:46:09 2017
Process finished with exit code 0
接着,我们将第一处代码的L38,做个倒序遍历,其他不变。
for i in reversed(nloops):
threads[i].join()
Lopper start at: Wed Aug 09 18:47:31 2017
Lopper 0 start at: Wed Aug 09 18:47:31 2017
Lopper 1 start at: Wed Aug 09 18:47:31 2017
Lopper 1 stop at: Wed Aug 09 18:47:33 2017
Lopper 0 stop at: Wed Aug 09 18:47:33 2017
Lopper stop at: Wed Aug 09 18:47:33 2017
Process finished with exit code 0
正序遍历和逆序遍历thread,分别调用join方法,而最后的结果完全相同,原因是:
两个方法都是在主线程调用的 所以根本不会关心哪个子线程先执行完 只要两个子线程都执行完了 在执行主线程 就是正确的结果