1. 多进程
使用包 multiprocessing ,多进程可以使用多核,但是资源开销较大,因为进程是操作系统资源分配的基本单位
1.1 相关语法:
import multiprocessing
import os
import time
def playBall():
for i in range(3):
print("play the ball game...")
time.sleep(3)
def playCard():
for i in range(3):
print("play the card game...")
time.sleep(1)
# 带参数的进程函数
def watchTV(clock, name):
for i in range(3):
print("正在看:", name)
time.sleep(clock)
# 获取进程的编号
def getID():
for i in range(3):
print("正在获取这个子进程的ID:", os.getpid())
print("正在获取这个子进程的父进程ID:", os.getppid())
time.sleep(1)
# 可以开启子进程守护,避免主进程等待子进程
# 使用函数:进程名.daemon = True
if __name__ == "__main__":
# 创建进程
ball_process = multiprocessing.Process(target=playBall)
card_process = multiprocessing.Process(target=playCard)
# 使用元组的形式进行传参,及时只有一个参数,第一个参数后面的逗号也不能省略
watch_process1 = multiprocessing.Process(target=watchTV, args=(1, "douluodalu"))
# 使用字典的形式进行传参
watch_process2 = multiprocessing.Process(target=watchTV, kwargs={"clock": 1, "name": "zhuzhuxia"})
getID_process = multiprocessing.Process(target=getID)
ball_process.daemon = True # 开启进程守护
ball_process.start() # 启动进程
card_process.daemon = True # 开启进程守护
card_process.start()
watch_process1.daemon = True # 开启进程守护
watch_process1.start()
watch_process2.daemon = True # 开启进程守护
watch_process2.start()
getID_process.daemon = True # 开启进程守护
getID_process.start()
# 主进程的6次循环过后,不管子进程是否执行完毕,会杀死所有子进程
# 如果不开启进程守护,则主进程执行完毕,会等着所有子进程执行结束后,程序才运行结束
for i in range(6):
print("正在获取主进程的ID:", os.getpid())
time.sleep(1)
print("main process finished...")
2. 多线程
使用包 Threading,多线程不能使用多核,但是资源开销较小,因为线程是CPU调度的基本单位
2.1 相关语法:
多线程和多进程的使用方法基本上是一样的,唯一的区别在于开启线程守护时,可以在创建子线程的时候直接指定是否开启线程守护,具体使用方式参照下方代码:
import threading
import os
import time
def playBall():
for i in range(3):
print("play the ball game...")
time.sleep(3)
def playCard():
for i in range(3):
print("play the card game...")
time.sleep(1)
# 带参数的线程函数
def watchTV(clock, name):
for i in range(3):
print("正在看:", name)
time.sleep(clock)
# 获取线程的编号
def getID():
for i in range(3):
print("正在获取这个子线程的ID:", os.getpid())
print("正在获取这个子线程的父线程ID:", os.getppid())
time.sleep(1)
# 可以开启子线程守护,避免主线程等待子线程
# 使用函数:线程名.daemon = True
if __name__ == "__main__":
# 创建线程
ball_thread = threading.Thread(target=playBall)
card_thread = threading.Thread(target=playCard)
# 使用元组的形式进行传参,及时只有一个参数,第一个参数后面的逗号也不能省略
watch_thread1 = threading.Thread(target=watchTV, args=(1, "douluodalu"))
# 使用字典的形式进行传参
watch_thread2 = threading.Thread(target=watchTV, kwargs={"clock": 1, "name": "zhuzhuxia"})
getID_thread = threading.Thread(target=getID,daemon=True) # 线程可以直接创建的时候指定开启守护,也可以在启动线程之前开启守护
ball_thread.daemon = True # 启动线程前开启守护
ball_thread.start() # 启动线程
card_thread.daemon = True
card_thread.start()
watch_thread1.daemon = True
watch_thread1.start()
watch_thread2.daemon = True
watch_thread2.start()
getID_thread.start()
# 主线程的6次循环过后,不管子线程是否执行完毕,会杀死所有子线程
# 如果不开启线程守护,则主线程执行完毕,会等着所有子线程执行结束后,程序才运行结束
for i in range(6):
print("正在获取主线程的ID:", os.getpid())
time.sleep(1)
print("main thread finished...")