线程vs进程
Posted marklijian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程vs进程相关的知识,希望对你有一定的参考价值。
线程vs进程
速度
from multiprocessing import Process
from threading import Thread
import time
def test():
pass
if __name__ == '__main__':
p = Process(target=test)
t = Thread(target=test)
start1 = time.time()
p.start()
p.join()
end1 = time.time()
start2 = time.time()
t.start()
t.join()
end2 = time.time()
print(end1 - start1)
print(end2 - start2)
线程要远快于进程
资源共享
from multiprocessing import Process
from threading import Thread
import time
x = 1
def test():
global x
x= 100
print("我完成了")
if __name__ == '__main__':
# 查看进程是否可修改数据
p = Process(target=test)
p.start()
time.sleep(2)
print(x)
# 查看线程是否可修改数据
# t = Thread(target=test)
# t.start()
#
# time.sleep(1)
# print(x)
线程共享资源
进程间彼此隔离
何时使用多进程 和 何时使用多进程
import time
from multiprocessing import Process
from threading import Thread,Timer
# 计算密集型函数
def compute_intensive():
res = 0
for i in range(10000000):
res += 1
def block_intensive():
time.sleep(3)
if __name__ == '__main__':
start = time.time()
p_l = []
for i in range(10):
p = Process(target=compute_intensive)
p_l.append(p)
p.start()
for i in p_l:
i.join()
end = time.time()
print("多进程计算密集型用时", end - start, '秒')
start1 = time.time()
t_l = []
for i in range(10):
t = Thread(target=compute_intensive)
t_l.append(t)
t.start()
for i in t_l:
i.join()
end1 = time.time()
print("多线程计算密集型用时", end1 - start1, '秒')
print()
start2 = time.time()
p_l = []
for i in range(10):
p = Process(target=block_intensive)
p_l.append(p)
p.start()
for i in p_l:
i.join()
end2 = time.time()
print("多进程IO密集型用时", end2 - start2, '秒')
start3 = time.time()
t_l = []
for i in range(10):
t = Thread(target=block_intensive)
t_l.append(t)
t.start()
for i in t_l:
i.join()
end3 = time.time()
print("多线程IO密集型用时", end3 - start3, '秒')
计算密集型使用多进程
IO密集型使用多线程
以上是关于线程vs进程的主要内容,如果未能解决你的问题,请参考以下文章