1.多线程初体验
主线程的id和进程的id是一个
查看进程pid下有多少个线程
ps -T -p pid
(base) D:\code\python_project\python_coroutine>C:/ProgramData/Anaconda3/python.exe d:/code/python_project/python_coroutine/01demo.py
threading.active_count=1
i am producer cnt=1 thread_id1 = 15984 thread_id2 = 15984
threading.active_count=2
i am consumer cnt=0 thread_id1 = 12828 thread_id2 = 12828
threading.active_count=3
i am producer cnt=1 thread_id1 = 15984 thread_id2 = 15984
i am consumer cnt=0 thread_id1 = 12828 thread_id2 = 12828
i am producer cnt=1 thread_id1 = 15984 thread_id2 = 15984
import threading
import time
cnt = 0
def producer():
global cnt
while True:
cnt += 1
print("i am producer cnt={} thread_id1 = {} thread_id2 = {}".format(cnt,threading.get_ident(), threading.get_native_id()))
time.sleep(1)
pass
def consumer():
global cnt
while True:
if cnt <= 0:
continue
cnt -= 1
print("i am consumer cnt={} thread_id1 = {} thread_id2 = {}".format(cnt,threading.get_ident(), threading.get_native_id()))
time.sleep(1)
if __name__ == "__main__":
print("threading.active_count={}".format(threading.active_count()))
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
print("threading.active_count={}".format(threading.active_count()))
t2.start()
print("threading.active_count={}".format(threading.active_count()))
查看当前程序的活跃线程数量
threading.active_count()
2.单线程下载器
下载模块:从网络上下载图片 I/O密集型
哈希模块:cpu密集
存储模块:I/O密集
单线程的是串行的,先下载,再哈希计算重命名,再存储,都是在主线程完成。
实际上三个功能应该并行起来:主线程负责调度,三个线程分别实现下载,哈希和存储。