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
相关文章
相关标签/搜索