[关闭]
@linux1s1s 2017-08-09T18:37:33.000000Z 字数 912 阅读 1321

Python 核心编程笔记四

Python 2017-08


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

CODE-多线程同步-Thread

  1. # -*- coding:gb18030 -*-
  2. # 线程同步 Thread
  3. import thread
  4. from time import ctime, sleep
  5. loops = [4, 2]
  6. def loop(loopName, sleepTime, locker):
  7. print 'Loop', loopName, 'begin at: ', ctime()
  8. sleep(sleepTime)
  9. print 'Loop', loopName, 'end at: ', ctime()
  10. locker.release()
  11. def main():
  12. print 'Loop begin at: ', ctime()
  13. lockers = []
  14. loopNames = range(len(loops))
  15. for i in loopNames:
  16. locker = thread.allocate_lock()
  17. locker.acquire()
  18. lockers.append(locker)
  19. for i in loopNames:
  20. thread.start_new_thread(loop, (i, loops[i], lockers[i]))
  21. sleep(loops[i])
  22. for i in loopNames:
  23. while lockers[i].locked():
  24. pass
  25. print 'Loop end at: ', ctime()
  26. if __name__ == '__main__':
  27. main()

RESULT

  1. C:\Python27\python.exe H:/workspace/python-hw/hw-5.py
  2. Loop begin at: Wed Aug 09 18:37:37 2017
  3. Loop 0 begin at: Wed Aug 09 18:37:37 2017
  4. Loop 0 end at: Wed Aug 09 18:37:41 2017
  5. Loop 1 begin at: Wed Aug 09 18:37:41 2017
  6. Loop 1 end at: Wed Aug 09 18:37:43 2017
  7. Loop end at: Wed Aug 09 18:37:43 2017
  8. Process finished with exit code 0
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注