標籤:cal import color 子進程 進程 style highlight %s xxxx
總結:
- 預設父線程跑完,子線程並不會馬上退出,不像 thread.start_threadXXXX
- 父線程跑完了,並沒有退出,一直在那裡
- 線程啟動速度很快,不佔多少開銷,不到1毫秒
代碼:
# -*- coding: utf-8 -*-"""學習 並發linux下執行"""from threading import Threadfrom multiprocessing import Processimport timeimport osimport psutildef work(): print(‘%s,%f: sub begin %d‘ % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time(),os.getpid())) print "%s,%f: sub %d,%d,%d" % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time(),os.getpid(),os.getppid(), psutil.Process(os.getpid()).num_threads()) time.sleep(5) print "%s,%f: sub %d,%d,%d" % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time(),os.getpid(),os.getppid(), psutil.Process(os.getpid()).num_threads()) print(‘%s,%f: sub end %d‘ % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time(),os.getpid()))if __name__ == ‘__main__‘: print "%s,%f: main begin" % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time()) print "%s,%f: main %d,%d,%d" % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time(),os.getpid(),os.getppid(), psutil.Process(os.getpid()).num_threads()) # 開啟子線程 t=Thread(target=work) t.start() print ‘%s,%f: main 線程‘ % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time()) print "%s,%f: main %d,%d,%d" % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time(),os.getpid(),os.getppid(), psutil.Process(os.getpid()).num_threads()) # 開啟子進程 # t=Process(target=work) # t.start() # print "\nmain %d,%d,%d" % (os.getpid(),os.getppid(), psutil.Process(os.getpid()).num_threads()) # print(‘\nmain 進程‘) print "%s,%f: main end" % (time.strftime(‘%M:%S‘,time.localtime(time.time())),time.time())
輸出:
格式說明:
小時 :秒,時間戳記, <當前進程ID, [父 進程ID,當前進程線程數量]>
[email protected]:~/python# python test_threadprocess1.py
----------------------------------------------------------
03:04,1536397384.349529: main begin
03:04,1536397384.349605: main 3604,2692,1
03:04,1536397384.350838: sub begin 3604
03:04,1536397384.350939: main 線程
03:04,1536397384.351009: sub 3604,2692,2
03:04,1536397384.351310: main 3604,2692,2
03:04,1536397384.352097: main end
03:09,1536397389.357353: sub 3604,2692,2
03:09,1536397389.358372: sub end 3604
----------------------------------------------------------
輸出解讀:
- 黃色 標記的中間 輸出部分 ,是啟動 子線程期間,這段 時間非常快,說明啟動線程的速度很快
- 紅色標記,此時main線程的邏輯 代碼跑完了,但是還是顯示有2個線程,對比開始,說明main線程並 沒有退出
python 歸納 (十一)_線程_threading.Thread