python3多进程和进程池
Posted fengzi7314
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3多进程和进程池相关的知识,希望对你有一定的参考价值。
#一个程序运行起来之后,代码+用到的资源称之为进程,它是操作系统分配资源的基本单位,不仅可以通过线程完成多任务,进程也是可以的
#进程之间是相互独立的
#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()
以上是关于python3多进程和进程池的主要内容,如果未能解决你的问题,请参考以下文章