总结:
- 默认父线程跑完,子线程并不会马上退出,不像 thread.start_threadXXXX
- 父线程跑完了,并没有退出,一直在那里
- 线程启动速度很快,不占多少开销,不到1毫秒
代码:
# -*- coding: utf-8 -*- """ 学习 并发 linux下执行 """ from threading import Thread from multiprocessing import Process import time import os import psutil def 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线程并 没有退出
原文地址:https://www.cnblogs.com/sunzebo/p/9609779.html
时间: 2024-11-04 15:34:08