python3多進程和進程池
阿新 • • 發佈:2018-11-26
適合 一個 from ssi pytho 進程 多進程並發 bsp col
#一個程序運行起來之後,代碼+用到的資源稱之為進程,它是操作系統分配資源的基本單位,不僅可以通過線程完成多任務,進程也是可以的
#進程之間是相互獨立的
#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多進程和進程池