[关闭]
@linux1s1s 2017-08-09T18:49:35.000000Z 字数 1953 阅读 1259

Python 核心编程笔记六

Python 2017-08


这里简要记录 Python核心编程 读书笔记 整段代码 可以直接运行

CODE-多线程同步-Threading-Class简单封装-1

  1. # -*- coding:gb18030 -*-
  2. # 线程同步 Threading + 简单类封装
  3. import threading
  4. from time import sleep, ctime
  5. loops = [2, 2]
  6. class ThreadFunc(object):
  7. def __init__(self, func, args, name=''):
  8. self.func = func
  9. self.args = args
  10. self.name = name
  11. def __call__(self, *args, **kwargs):
  12. apply(self.func, self.args)
  13. def loop(nloop, during):
  14. print 'Lopper ', nloop, 'start at: ', ctime()
  15. sleep(during)
  16. print 'Lopper ', nloop, 'stop at: ', ctime()
  17. def main():
  18. print 'Lopper start at: ', ctime()
  19. threads = []
  20. nloops = range(len(loops))
  21. for i in nloops:
  22. t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
  23. threads.append(t)
  24. for i in nloops:
  25. threads[i].start()
  26. for i in nloops:
  27. threads[i].join()
  28. print 'Lopper stop at: ', ctime()
  29. if __name__ == '__main__':
  30. main()

RESULT-多线程同步-Threading-Class简单封装-1

  1. C:\Python27\python.exe H:/workspace/python-hw/hw-7.py
  2. Lopper start at: Wed Aug 09 18:44:41 2017
  3. Lopper 0 start at: Wed Aug 09 18:44:41 2017
  4. Lopper 1 start at: Wed Aug 09 18:44:41 2017
  5. Lopper 1 stop at: Wed Aug 09 18:44:43 2017
  6. Lopper 0 stop at: Wed Aug 09 18:44:43 2017
  7. Lopper stop at: Wed Aug 09 18:44:43 2017
  8. Process finished with exit code 0

CODE-多线程同步-Threading-Class简单封装-2

我们将上面代码中L36-40 合并在一个遍历中,其他不变

  1. for i in nloops:
  2. threads[i].start()
  3. threads[i].join()

RESULT-多线程同步-Threading-Class简单封装-2

  1. C:\Python27\python.exe H:/workspace/python-hw/hw-7.py
  2. Lopper start at: Wed Aug 09 18:46:05 2017
  3. Lopper 0 start at: Wed Aug 09 18:46:05 2017
  4. Lopper 0 stop at: Wed Aug 09 18:46:07 2017
  5. Lopper 1 start at: Wed Aug 09 18:46:07 2017
  6. Lopper 1 stop at: Wed Aug 09 18:46:09 2017
  7. Lopper stop at: Wed Aug 09 18:46:09 2017
  8. Process finished with exit code 0

CODE-多线程同步-Threading-Class简单封装-3

接着,我们将第一处代码的L38,做个倒序遍历,其他不变。

  1. for i in reversed(nloops):
  2. threads[i].join()

RESULT-多线程同步-Threading-Class简单封装-3

  1. Lopper start at: Wed Aug 09 18:47:31 2017
  2. Lopper 0 start at: Wed Aug 09 18:47:31 2017
  3. Lopper 1 start at: Wed Aug 09 18:47:31 2017
  4. Lopper 1 stop at: Wed Aug 09 18:47:33 2017
  5. Lopper 0 stop at: Wed Aug 09 18:47:33 2017
  6. Lopper stop at: Wed Aug 09 18:47:33 2017
  7. Process finished with exit code 0

小结

正序遍历和逆序遍历thread,分别调用join方法,而最后的结果完全相同,原因是:
两个方法都是在主线程调用的 所以根本不会关心哪个子线程先执行完 只要两个子线程都执行完了 在执行主线程 就是正确的结果

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注