进行多进程方式操作:
多进程需要用到Queue管道方式进行处理,这样就是用的共同内存数据
进程进行start后,主进程很快结束,但是子进程还是在后台运行直到结束,如需要等子进程结束后再结束主进程需要join
"""
multiprocessing.Queue : 管道 序列化 进程安全
了解: MQ (Message Queue) Redis rabitMq kafka
"""
from multiprocessing import Process, Queue
def work01(q: Queue):
"""
:param q: 要处理的所有任务
:return: None
"""
print('work01中的参数q的id:', id(q))
while not q.empty():
print(f'work01从q中获得了{q.get()}')
def work02(q: Queue):
"""
:param q: 要做的所有任务
:return: None
"""
print('work02中的参数q的id:', id(q))
while not q.empty():
print(f'work02 从q中获得了{q.get()}')
if __name__ == '__main__':
q = Queue()
q.put('a')
q.put('b')
q.put('c')
p1 = Process(target=work01, args=(q,)) # 子进程 q1
p2 = Process(target=work02, args=(q,)) # 子进程 q2
p1.start()
p2.start()
print(f'主进程运行完毕!')
# 使用list: work01 work02会做重复工作 p1 p2 进程 独享 list内存
# 使用Queue: work01 work02共同完成q中的所有任务 Queue 是被 p1 p2 共享的
import os
import time
from multiprocessing import Process
def play_music():
print("子进程p1:", os.getpid())
for i in range(5):
print('play music ...')
time.sleep(1)
def play_lol():
print("子进程p2:", os.getpid())
for i in range(5):
print('play lol ...')
time.sleep(1)
if __name__ == '__main__':
print('主进程:', os.getpid())
start_time = time.time()
p1 = Process(target=play_music)
p2 = Process(target=play_lol)
# p1.daemon = True # 默认值是False,当为True的时候,主进程结束,会强制结束子进程
# p2.daemon = True
p1.start() # 操作系统 启动一个进程 用来运行target=play_music 的 进程,子进程 (不是完整的代码)
# p1.join() # 上面的代码任务没有执行完,不会运行下面的代码
p2.start()
print(help(p2))
# p1.join()
# p2.join()
# p1 p2 都结束后再 计算时间
# while True:
# if p1.is_alive() or p2.is_alive():
# time.sleep(1)
# else:
# break
end_time = time.time()
print(end_time - start_time)
# 怎么才能保证让主进程最后再结束呢? 用join
# 主进程: 进程基础.py (代码) python.exe 进程基础.py 运行的时候, 操作系统会 分一个进程, 这个进程我们称为主进程
# p1.daemon
# is_alive()
多进程类的操作:就是继承process类,重写run方法
from multiprocessing import Process
class MyProcess(Process):
def __init__(self):
super().__init__()
def run(self):
print("hello ")
if __name__ == '__main__':
p1 = MyProcess()
p2 = MyProcess()
p1.start() # 会调用 MyProcess中的run方法
p2.start()
多线程操作:
进行多线程操作引入threading就可以
import threading
import time
def music(user):
print(f'{user}正在听音乐....')
print(f'{threading.current_thread().name}正在运行...')
time.sleep(5)
print(f'{threading.current_thread().name}运行即将结束。')
def lol(user):
time.sleep(8)
if __name__ == '__main__':
t1 = threading.Thread(target=music, args=('无极',), name='线程1')
t2 = threading.Thread(target=lol, args=('无极',), name='线程2')
t1.start()
t2.start()
# t1.join() # 阻塞主程序,但不会阻塞线程2
# t2.join()
print('主程序结束!')