进程和线程
python里面的多进程
unix和linux
使用fork() 来调用系统创建一个进程
这样创建的进程是一个子进程,拷贝的父进程的
但是子进程都存在自己的PID
fork的它可以做到返回两次
在父进程里fork返回的是子进程的PID,在子进程里返回的永远都是0
win
multiprocessing
使用这个model里面的Process创建子进程
并且在这个里面还进行了更高级的封装
进程池(pool) 消息队列(Queue) 管道(Pipe)
下面是一段对比
不适用多进程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26from time import time, sleep
# 不使用多进程
def work_out():
start = time()
all = 1
for i in range(1, 100000):
all = all * i
# print(all)
end = time()
print(f"消耗的时间为 :{end-start}\n")
def main():
start = time()
work_out()
work_out()
end = time()
print(f"消耗时间为:{end-start}")
if __name__ == "__main__":
main()消耗的时间为 :2.4721951484680176
消耗的时间为 :2.4349334239959717
消耗时间为:4.907128572463989
使用多进程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31from time import time, sleep
from multiprocessing import Process
# 使用多进程
def work_out():
start = time()
all = 1
for i in range(1, 100000):
all = all * i
# print(all)
end = time()
print(f"消耗的时间为 :{end-start}\n")
def main():
start = time()
p1 = Process(target=work_out)
p1.start()
p2 = Process(target=work_out)
p2.start()
p1.join()
p2.join()
end = time()
print(f"消耗时间为:{end-start}")
if __name__ == "__main__":
main()消耗的时间为 :3.135038137435913
消耗的时间为 :3.1490530967712402
消耗时间为:3.279216766357422
也可以使用subprocess模块中类
创建子进程,然后子进程之间可以访问
python里的多线程
主要使用的是
threading
来实现多线程多线程之间可以通信,因为共用,但是就会面临一个新的问题
如果两个线程同时访问一个全局变量会发生什么结果?
这个变量称为竞争变量
加锁解决
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31from threading import Thread, Lock
i = 0
total = 0
lock = Lock()
def work():
global i, total
while i != 101:
lock.acquire()
total += i
i += 1
lock.release()
def main():
t1 = Thread(target=work)
t1.start()
t2 = Thread(target=work)
t2.start()
t1.join()
t2.join()
print(f"结果是: {total}")
if __name__ == "__main__":
main()
python里面的协程
- 优势
- 运行效率极高
- 可以在单核单线程里面处理异步操作
- 不需要锁机制
- 如果想要充分利用CPU的多核特性,最简单的方法是多进程+协程,既充分利用多核,又充分发挥协程的高效率
进程和线程
https://tsy244.github.io/2023/10/23/python/进程和线程/