@linux1s1s
2017-08-09T18:37:33.000000Z
字数 912
阅读 1315
Python
2017-08
这里简要记录
Python核心编程
读书笔记 整段代码 可以直接运行
# -*- coding:gb18030 -*-
# 线程同步 Thread
import thread
from time import ctime, sleep
loops = [4, 2]
def loop(loopName, sleepTime, locker):
print 'Loop', loopName, 'begin at: ', ctime()
sleep(sleepTime)
print 'Loop', loopName, 'end at: ', ctime()
locker.release()
def main():
print 'Loop begin at: ', ctime()
lockers = []
loopNames = range(len(loops))
for i in loopNames:
locker = thread.allocate_lock()
locker.acquire()
lockers.append(locker)
for i in loopNames:
thread.start_new_thread(loop, (i, loops[i], lockers[i]))
sleep(loops[i])
for i in loopNames:
while lockers[i].locked():
pass
print 'Loop end at: ', ctime()
if __name__ == '__main__':
main()
C:\Python27\python.exe H:/workspace/python-hw/hw-5.py
Loop begin at: Wed Aug 09 18:37:37 2017
Loop 0 begin at: Wed Aug 09 18:37:37 2017
Loop 0 end at: Wed Aug 09 18:37:41 2017
Loop 1 begin at: Wed Aug 09 18:37:41 2017
Loop 1 end at: Wed Aug 09 18:37:43 2017
Loop end at: Wed Aug 09 18:37:43 2017
Process finished with exit code 0