欢迎来到无荨的博客

想一千次,不如去做一次。如果自己不努力,那么这一辈子只可能在原地踏步!

python——多进程

进程:

  一个程序运行起来之后,代码+用到的资源称之为进程,它是操作系统分配资源的基本单位。不仅可以通过线程完成多任务,进程也是可以的。

  调用:import multiprocessing

  •   python的多进程是真真正正的利用了cpu的多核
  •   进程之间是相互独立的
  •   不共享、互不干涉,进程间有隔离性
  •   耗费的资源大,效率高
  •   cpu密集的时候适合用多进程

进程的几种用法:
1、没有参数
  不能直接启动,需要加‘__name__ ==' __main__' ’
  真真正正的利用了cpu的多核

 

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

  

2、有参数时

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


3、进程池
 库的导入方法
  1、from multiprocessing import Pool(调用方法:pool)
  2、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()

结果:
1、
    (pool = Pool(2))
	test1~0
	test2~0
    …
	test1~3
	test2~3
	test3~0
	test4~0
	…
2、
    pool = Pool(4)
	test1~0
	test4~0
	test2~0
	test3~0

4、不共享、互不干涉,进程间有隔离性

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
posted @ 2019-10-23 07:34  无荨  阅读(189)  评论(0编辑  收藏  举报