标签:import == 独立 多进程 art proc 分配 main style
#一个程序运行起来之后,代码+用到的资源称之为进程,它是操作系统分配资源的基本单位,不仅可以通过线程完成多任务,进程也是可以的
#进程之间是相互独立的
#cpu密集的时候适合用多进程
#多进程并发 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()
#进程之间不共享 import multiprocessing from multiprocessing import Pool import time import threading g_num = 0 def edit(): global g_num for i in range(10): g_num += 1 def reader(): print(g_num) if __name__ == ‘__main__‘: # t1 = threading.Thread(target=edit) # t2 = threading.Thread(target=reader) # t1.start() # t2.start() p1 = multiprocessing.Process(target=edit) p2 = multiprocessing.Process(target=reader()) p1.start() p1.join() p2.start()
#进程池实现并发 import multiprocessing from multiprocessing import Pool import time import threading g_num = 0 def test1(): for i in range(10): time.sleep(1) print(‘test1‘, i) def test2(): for i in range(10): time.sleep(1) print(‘test2‘, i) if __name__ == ‘__main__‘: # t1 = threading.Thread(target=edit) # t2 = threading.Thread(target=reader) # t1.start() # t2.start() # p1 = multiprocessing.Process(target=edit) # p2 = multiprocessing.Process(target=reader()) # p1.start() # p1.join() # p2.start() pool = Pool() pool.apply_async(test1) pool.apply_async(test2) pool.close() pool.join()
标签:import == 独立 多进程 art proc 分配 main style
原文地址:https://www.cnblogs.com/fengzi7314/p/10017580.html