import thread
from time import sleep, ctime
loops = [4,2]
def loop0():
print 'start loop 0 at:', ctime()
sleep(4)
print 'loop 0 done at:', ctime()
def loop1():
print 'start loop 1 at:', ctime()
sleep(2)
print 'loop 1 done at:', ctime()
def main():
print 'start:', ctime()
a=thread.start_new_thread(loop0, ())
thread.start_new_thread(loop1, ())
sleep(6)
print 'all end:', ctime()
if __name__ == '__main__':
main()
說明:
當腳本啟動,實際就是啟動了一個主線程,當主線程跑完,子線程也會隨之關閉(無亂是否執行完)
主線程和子線程是同時執行的
我們可以把sleep(6)的位置改成去外部txt文件 查詢值,當值為1 那么主線程跑完,子線程也隨之的關閉掉
后記: 子線程都執行完了,主線程才關閉 的寫法
#coding=utf-8
import thread
from time import sleep,ctime
def loop(nloop,lock):
print 'start loop', nloop, 'at:', ctime()
sleep(1)
print 'loop', nloop, 'done at:', ctime()
#解鎖
lock.release()
def main():
print 'starting at:', ctime()
locks =[]
#創建2個帶鎖的對象
for i in range(2):
# 返回一個新的鎖定對象,創建一個鎖的列表
lock = thread.allocate_lock()
# 一個原始的鎖有兩種狀態,鎖定與解鎖,分別對應 acquire()和 release() 方法。
#鎖定
lock.acquire()
#追加到 locks[]數組中 ,放到鎖列表 locks中
locks.append(lock)
#執行多線程(創建2條線程並帶上鎖)
for i in range(2):
thread.start_new_thread(loop,(i,locks[i]))
#循環監控,這2條帶鎖的線程,是否解鎖,都解鎖了 主線程就退出,腳本執行完畢
for i in range(2):
while locks[i].locked():
pass
print 'all end:', ctime()
if __name__ == '__main__':
main()