Python多进程与多线程
一、多进程
进程(Process)是资源分配的最小单位,它是操作系统进行资源分配和调度运行的基本单位,通俗理解,一个正在运行的程序就是一个进程,例如正在运行的QQ……
多进程就是相对于同时运行多个程序,每个程序间相互独立
1.进程创建
import multiprocessing
import time
def dance():
for i in range(3):
print('i am dancing')
time.sleep(1)
def sing():
for i in range(3):
print(' i am singing')
time.sleep(1)
if __name__ == '__main__':
start = time.time()
#创建进程类
dancing = multiprocessing.Process(target=dance)
signing = multiprocessing.Process(target=sing)
dancing.start()
signing.start()
#主进程需要等待子进程运行完毕
dancing.join()
signing.join()
#打印总共花费时间
print(time.time() - start)
2.给进程添加参数
import multiprocessing
import time
def dance(name, num):
for i in range(num):
print(f'{name}: i am dancing')
time.sleep(1)
def sing(name, num):
for i in range(num):
print(f'{name}: i am singing')
time.sleep(1)
if __name__ == '__main__':
start = time.time()
#通过元祖传参
dancing = multiprocessing.Process(target=dance, args=('xiaoming',3))
#通过字典传参
signing = multiprocessing.Process(target=sing, kwargs={"name":'xiaohong', "num":3})
dancing.start()
signing.start()
dancing.join()
signing.join()
print(time.time() - start)
3.进程顺序
import multiprocessing
import time
def dance(name, num):
for i in range(num):
print(f'{name}: i am dancing')
time.sleep(1)
def sing(name, num):
for i in range(num):
print(f'{name}: i am singing')
time.sleep(1)
if __name__ == '__main__':
start = time.time()
dancing = multiprocessing.Process(target=dance, args=('xiaoming',3))
signing = multiprocessing.Process(target=sing, kwargs={"name":'xiaohong', "num":3})
dancing.start()
signing.start()
print(time.time() - start)
默认情况主进程会等待所有的子进程执行结束后再结束
3.1设置守护进程,主进程不会等待守护进程
import multiprocessing
import time
def dance(name, num):
for i in range(num):
print(f'{name}: i am dancing')
time.sleep(1)
def sing(name, num):
for i in range(num):
print(f'{name}: i am singing')
time.sleep(1)
if __name__ == '__main__':
start = time.time()
dancing = multiprocessing.Process(target=dance, args=('xiaoming',3))
signing = multiprocessing.Process(target=sing, kwargs={"name":'xiaohong', "num":3})
dancing.daemon = True
signing.daemon = True
dancing.start()
signing.start()
time.sleep(1)
print(time.time() - start)
二、多线程
和进程代码差不多
from threading import Thread
import time
def dance(name, num):
for i in range(num):
print(f'{name}: i am dancing')
time.sleep(1)
def sing(name, num):
for i in range(num):
print(f'{name}: i am singing')
time.sleep(1)
if __name__ == '__main__':
start = time.time()
# 元祖传参
dancing = Thread(target=dance, args=('xiaoming', 3))
# 字典传参
signing = Thread(target=sing, kwargs={"name":'xiaohong', "num":3})
# 设置守护线程
dancing.daemon = True
signing.daemon = True
# 线程启动
dancing.start()
signing.start()
# 主线程需要等待子线程完成
dancing.join()
signing.join()
time.sleep(1)
print(time.time() - start)
t()
# 主线程需要等待子线程完成
dancing.join()
signing.join()
time.sleep(1)
print(time.time() - start)
[外链图片转存中...(img-6EoQLKMo-1704506723532)]