-
知识要点
1、导入进程包:
import multiprocessing
2、创建子进程并指定执行的任务:
进程对象 = multiprocessing.Process(target=任务名)
3、启动进程执行任务:
进程对象.start()
-
代码示例
import time
import multiprocessing
# 编写代码
def coding():
for i in range(3):
print("coding...")
time.sleep(0.2)
# 听音乐
def music() -> object:
for i in range(3):
print("music...")
time.sleep(0.2)
if __name__ == '__main__':
# coding()
# music()
# 通过进程类创建进程对象
coding_process = multiprocessing.Process(target=coding)
music_process = multiprocessing.Process(target=music)
# 启动进程
coding_process.start()
music_process.start()
-
执行效果
带参数的多进程示例
知识点.pngimport time
import multiprocessing
# 编写代码
def coding(num):
for i in range(num):
print("coding...")
time.sleep(0.2)
# 听音乐
def music(count) -> object:
for i in range(count):
print("music...")
time.sleep(0.2)
if __name__ == '__main__':
# coding()
# music()
# 通过进程类创建进程对象
coding_process = multiprocessing.Process(target=coding, args=(3,))
music_process = multiprocessing.Process(target=music, kwargs={"count": 2})
# 启动进程
coding_process.start()
music_process.start()
网友评论