python——多進程

進程:python

  一個程序運行起來以後,代碼+用到的資源稱之爲進程,它是操做系統分配資源的基本單位。不只能夠經過線程完成多任務,進程也是能夠的。app

  調用:import multiprocessingasync

  •   python的多進程是真真正正的利用了cpu的多核
  •   進程之間是相互獨立的
  •   不共享、互不干涉,進程間有隔離性
  •   耗費的資源大,效率高
  •   cpu密集的時候適合用多進程

進程的幾種用法:
一、沒有參數
  不能直接啓動,須要加‘__name__ ==' __main__' ’
  真真正正的利用了cpu的多核spa

 

eg:
import multiprocessing
import time
def test1():
    for i in range(5):
        time.sleep(1)
        print('test1~{}'.format(i))

def test2():
    for i in range(5):
        print('test2~{}'.format(i))
        time.sleep(1)

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=test1)
    p2 = multiprocessing.Process(target=test2)
    p1.start()
    p2.start()

結果:
    test2~0
    test1~0
    test2~1
    test1~1
    test2~2
    test1~2
    test2~3
    test1~3
    test2~4
    test1~4

  

二、有參數時操作系統

import multiprocessing
import time

def test1(n):
    for i in range(n):
        time.sleep(1)
        print('test1~{}'.format(i))

def test2(n):
    for i in range(n):
        print('test2~{}'.format(i))
        time.sleep(1)

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=test1,args=(5,))
    p2 = multiprocessing.Process(target=test2,args=(4,))
    p1.start()
    p2.start()

結果:
    test2~0
    test1~0
    test2~1
    test1~1
    test2~2
    test1~2
    test2~3
    test1~3
    test1~4


三、進程池
 庫的導入方法
  一、from multiprocessing import Pool(調用方法:pool)
  二、import multiprocessing.pool(調用方法:multiprocessing.pool)
 XXX=Pool(NUM) :NUM表明調用的數量,調用幾個就運行幾個
 必定是先關閉,後運行 pool.close() pool.join()線程

eg:
import multiprocessing
from multiprocessing import Pool
import time

def test1():
    for i in range(4):
        time.sleep(1)
        print('test1~{}'.format(i))

def test2():
    for i in range(4):
        time.sleep(1)
        print('test2~{}'.format(i))

def test3():
    for i in range(4):
        time.sleep(1)
        print('test3~{}'.format(i))

def test4():
    for i in range(4):
        time.sleep(1)
        print('test4~{}'.format(i))

if __name__ == '__main__':
    pool = Pool(2)                      #Pool(NUM)調用的數量,調用幾個就運行幾個
    pool.apply_async(test1)
    pool.apply_async(test2)
    pool.apply_async(test3)
    pool.apply_async(test4)
    pool.close()                        #必定是先關閉,後運行
    pool.join()

結果:
一、
    (pool = Pool(2))
	test1~0
	test2~0
    …
	test1~3
	test2~3
	test3~0
	test4~0
	…
二、
    pool = Pool(4)
	test1~0
	test4~0
	test2~0
	test3~0

四、不共享、互不干涉,進程間有隔離性orm

import multiprocessing
import time

n = 0
def test1():
    global n
    for i in range(10):
        n += 1
    print('test1:',n)

def test2():
    global n
    for i in range(10):
        n += 1
    print('test2:', n)

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=test1)
    p2 = multiprocessing.Process(target=test2)
    p1.start()
    p2.start()
    print('全局:',n)

結果:
    全局: 0
    test1: 10
    test2: 10
相關文章
相關標籤/搜索