一 线程的基本概念
1.1 进程和线程
进程是资源分配的最小单位
线程是计算机中调度的最小单位
进程池:
开启过多的进程并不一走提高你的效率,
如果cp负载任务过多,平均单个任务执行的效率就会低,反而降低执行速度
- 1个人做4件事,4个人做4件事,4个人做1件事
- 显然后者执行速度更快,
- 前者是并发,后者是并行
- 利用进程池,可以开启cpu的并行效果
开启进程
- apply 开启进程,同步阻塞,每欠都都要等待当前任务完成之后,在开启下一个进程
- apply_async 开启进程,异步非咀塞,(主进程和子进程异步
1.2 线程的缘起
- 资源分配需要分配内存空间,分配cpu
- 分配的内存空间存放着临时要处理的数据等,比如要执行的代码,数据
- 而这些内存空间是有限的,不能无限分配
- 目前配置高的主机,5万个并发已是上限线程概念应用而生
1.3 线程的特点
- 线程是比较轻量级,能干更多的活,一个进程中的所有线程沒源是共享的
- 一个进程至少有一个线程在工作
二 线程的基本使用
2.1 一个进程可以有多个线程,共享同一份资源
from threading import Thread
from multiprocessing import Process
import random,time,os
def func(num):
time.sleep(random.uniform(0.1,1))
print("子线程",num,os.getpid())
for i in range(10):
t = Thread(target=func,args=(i,))
t.start()
执行
[root@node10 python]# python3 test.py 子线程 7 4937 子线程 9 4937 子线程 6 4937 子线程 1 4937 子线程 5 4937 子线程 8 4937 子线程 0 4937 子线程 3 4937 子线程 4 4937 子线程 2 4937
2.2 并发多线程 和 并发多进程 的速度对比
多线程更快
计算线程的时间
from threading import Thread
from multiprocessing import Process
import random,time,os
def func(i):
# time.sleep(random.uniform(0.1,1))
print("子线程",i,os.getpid())
# starttime = time.time()
# endtime = time.time()
# 1.计算多线程的时间
startime = time.perf_counter()
lst = []
for i in range(10000):
t = Thread(target=func,args=(i,))
t.start()
lst.append(t)
for i in lst:
i.join()
endtime = time.perf_counter()
print(endtime-startime,"主线程执行结束===================")
执行跑一万个线程
[root@node10 python]# python3 test.py

计算多进程的时间
from threading import Thread
from multiprocessing import Process
import random,time,os
def func(i):
# time.sleep(random.uniform(0.1,1))
print("子线程",i,os.getpid())
# starttime = time.time()
# endtime = time.time()
# 1.计算多线程的时间
startime = time.perf_counter()
lst = []
for i in range(1000):
t = Thread(target=func,args=(i,))
t.start()
lst.append(t)
for i in lst:
i.join()
endtime = time.perf_counter()
print(endtime-startime,"主线程执行结束===================")
startime = time.perf_counter()
lst = []
for i in range(1000):
p = Process(target=func,args=(i,))
p.start()
lst.append(p)
for i in lst:
i.join()
endtime = time.perf_counter()
print(endtime-startime,"主进程执行结束======================")
执行
线程时间

进程时间

2.3 多线程共享同一份进程资源
from threading import Thread
from multiprocessing import Process
import random,time,os
num = 100
lst = []
def func(i):
global num
num -= 1
for i in range(100):
t =Thread(target=func,args=(i,))
t.start()
lst.append(t)
for i in lst:
i.join()
print(num)
执行
[root@node10 python]# python3 test.py 0
三 线程相关函数
- 线程.is_alive() 检测线程是否仍然存在
- 线程.setName() 设置线程名字
- 线程.getName() 获取线程名字
- 1.currentThread().ident 查看线程id号
- 2.enumerate() 返回目前正在运行的线程列表
- 3.activeCount() 返回目前正在运行的线程数量
3.1 线程.is_alive()
from threading import Thread
from multiprocessing import Process
import random,time,os
def func():
pass
t = Thread(target=func)
t.start()
print(t.is_alive())
执行
[root@node10 python]# python3 test.py False
修改
from threading import Thread
from multiprocessing import Process
import random,time,os
def func():
time.sleep(0.5)
t = Thread(target=func)
t.start()
print(t.is_alive())
执行
[root@node10 python]# python3 test.py True
3.2 setName() 和getName()
from threading import Thread
from multiprocessing import Process
import random,time,os
def func():
time.sleep(0.5)
t = Thread(target=func)
t.start()
print(t.is_alive())
t.setName("消费者")
print (t.getName())
执行
[root@node10 python]# python3 test.py True 消费者
3.3 currentThread().ident 查看线程id号
from threading import Thread,currentThread
from multiprocessing import Process
import random,time,os
def func():
print ("子线程:",currentThread().ident)
t = Thread(target=func)
t.start()
print ("主线程:",currentThread().ident,os.getpid())
执行
[root@node10 python]# python3 test.py 子线程: 140242991515392 主线程: 140243176634176 41240
3.4 enumerate()返回目前正在运行的线程列表
from threading import Thread,currentThread,enumerate
from multiprocessing import Process
import random,time,os
def func():
print ("子线程:",currentThread().ident)
time.sleep(0.5)
for i in range(10):
t = Thread(target=func)
t.start()
print (enumerate())
执行
子线程: 140043211654912 子线程: 140043203262208 子线程: 140043194869504 子线程: 140042978719488 子线程: 140042970326784 子线程: 140042961934080 子线程: 140042953541376 子线程: 140042945148672 子线程: 140042936755968 子线程: 140042928363264 [<_MainThread(MainThread, started 140043396773696)>,
<Thread(Thread-1, started 140043211654912)>,
<Thread(Thread-2, started 140043203262208)>,
<Thread(Thread-3, started 140043194869504)>,
<Thread(Thread-4, started 140042978719488)>,
<Thread(Thread-5, started 140042970326784)>,
<Thread(Thread-6, started 140042961934080)>,
<Thread(Thread-7, started 140042953541376)>,
<Thread(Thread-8, started 140042945148672)>,
<Thread(Thread-9, started 140042936755968)>,
<Thread(Thread-10, started 140042928363264)>]
11
3.5 activeCount() 返回目前正在运行的线程数量
from threading import Thread,currentThread,enumerate
from multiprocessing import Process
import random,time,os
from threading import activeCount
def func():
print ("子线程:",currentThread().ident)
time.sleep(0.5)
for i in range(10):
t = Thread(target=func)
t.start()
print (enumerate())
print(activeCount())
执行
[root@node10 python]# python3 test.py 子线程: 140087921592064 子线程: 140087913199360 子线程: 140087904806656 子线程: 140087896413952 子线程: 140087888021248 子线程: 140087539005184 子线程: 140087530612480 子线程: 140087522219776 子线程: 140087513827072 子线程: 140087505434368 [<_MainThread(MainThread, started 140088106710848)>, <Thread(Thread-1, started 140087921592064)>, <Thread(Thread-2, started 140087913199360)>, <Thread(Thread-3, started 140087904806656)>, <Thread(Thread-4, started 140087896413952)>, <Thread(Thread-5, started 140087888021248)>, <Thread(Thread-6, started 140087539005184)>, <Thread(Thread-7, started 140087530612480)>, <Thread(Thread-8, started 140087522219776)>, <Thread(Thread-9, started 140087513827072)>, <Thread(Thread-10, started 140087505434368)>] 11
3.6 守护线程
等待所有线程执行结束之后,在自动结束,守护所有线程
from threading import Thread
import time
def func1():
#这里定义一个死循环,可以一直跑
while True:
print ("This is Thread 1,func1")
def func2():
print ("This is Thread 2,and I will start run")
time.sleep(0.05)
print ("This is Thread 2,and I have aready end")
#启动线程1
t1 = Thread(target=func1)
#因为线程1是死循环状态,可以给这个线程设置一个守护线程,当所有线程都执行完,结束这个线程
t1.setDaemon(True)
t1.start()
#启动线程2
t2 = Thread(target=func2)
t2.start()
print("Main Thread has aready stop run")
