code
macname@MacdeMBP Desktop % macname@MacdeMBP Desktop % cat test.py import time from multiprocessing import Process def func(name): print(f"我是{name}开始") time.sleep(0.5) print(f"我是{name}结束") if __name__ == '__main__': p1 = Process(target=func, args=("进程1",)) p1.start() print("主进程执行结束,子进程是依附于主进程存在的,所以,子进程都结束后,主进程才真正的结束。") macname@MacdeMBP Desktop % python3 test.py 主进程执行结束,子进程是依附于主进程存在的,所以,子进程都结束后,主进程才真正的结束。 我是进程1开始 我是进程1结束
code2
import multiprocessing from multiprocessing import Pool import time import threading g_num = 0 def test1(): global g_num for i in range(10): g_num += 1 def test2(): print(g_num) if __name__ == '__main__': p1 = multiprocessing.Process(target=test1) p2 = multiprocessing.Process(target=test2) p1.start() p1.join() p2.start() print("main")
code3
import multiprocessing from multiprocessing import Pool import time def test1(): for i in range(10): time.sleep(1) print('test', i) def test2(): for i in range(10): time.sleep(1) print('test', i) if __name__ == '__main__': p1 = multiprocessing.Process(target=test1) p2 = multiprocessing.Process(target=test2) p1.start() p2.start() print("main")