1、进程
import multiprocessing
import time
import os
def ad(num):
print("进程1编号:",os.getpid())
print("进程1父进程编号:",os.getppid())
for i in range(num):
print("我是第一个进程\n")
time.sleep(0.5)
def bd(num):
print("进程2编号:",os.getpid())
print("进程2父进程编号:",os.getppid())
for i in range(num):
print("我是第二个进程\n")
time.sleep(0.5)
if __name__ == '__main__':
'''
1、os.getpid()表示获取当前进程编号
2、os.geppid()表示获取当前父亲编号
3、args表示元祖类型,可以给函数传递参数;
4、kwargs表示字典类型,可以给函数传递参数;
5、默认情况下,主进程结束,子进程会继续执行;
6、进程名.deamon = Ture 语句表示主进程结束,子进程也结束;
7、加上进程名.join()表示该进程结束后再执行主进程
'''
print("主进程编号:",os.getpid())
one_pre = multiprocessing.Process(target=ad,args=(5,))
two_pre = multiprocessing.Process(target=bd,kwargs={"num":5})
one_pre.deamon = True
one_pre.start()
two_pre.start()
one_pre.join()
two_pre.join()
print("此时该处打印的消息会在one_pre和two_pre结束后才显示出来!")
2、线程
import threading
import time
import os
def bsball(num):
for i in range(num):
print("打篮球...")
time.sleep(0.2)
def ppball(num):
for i in range(num):
print("打乒乓球...")
time.sleep(0.2)
if __name__ == "__main__":
print(os.getpid())
bs = threading.Thread(target = bsball,args = (2,),daemon=True)
pp = threading.Thread(target = ppball,kwargs = {"num":2})
bs.start()
pp.start()