多进程

1、queue

import threading as td
import multiprocessing as mp
def job(q,a,b):
    q.put(a**b)

if __name__ == "__main__":
    q=mp.Queue()
    t2=mp.Process(target=job,args=(q,3,3))
    t1=mp.Process(target=job,args=(q,4,3))
    t2.start()
    t2.join()
    t1.start()
    t1.join()
    res1=q.get()
    res2=q.get()
    print(res1)
    print(res2)

2、进程池

import threading as td
import multiprocessing as mp

def job(x):
    return x*x

def multicore():
    pool=mp.Pool()
    res=pool.map(job,range(100))
    print(res)

if __name__ == "__main__":
    multicore()

3、apply_async

import threading as td
import multiprocessing as mp
from time import *

def job(x):
    return x*x

def multicore():
    pool=mp.Pool(processes=3)
    res=pool.map(job,range(4))
    print(res)
    res=pool.apply_async(job,(2,))
    print(res)
    multi_res=[pool.apply_async(job,(i,)) for i in range(12)]
    print([resa.get() for resa in multi_res])

if __name__ == "__main__":
    t1=time()
    multicore()
    t2=time()
    print(t2-t1)

4、共享内存

import threading as td
import multiprocessing as mp
from time import *

def job(v,num,l):
    l.acquire()
    for _ in range(10):
        sleep(0.2)
        v.value+=num
        print(v.value)
    l.release()
    # return x*x

def multicore():
    i=mp.Lock()
    v=mp.Value("i",0)
    p1=mp.Process(target=job,args=(v,1,i))
    p2=mp.Process(target=job,args=(v,3,i))
    p1.start()
    p2.start()
    p1.join() 
    p2.join()

if __name__ == "__main__":
    t1=time()
    multicore()
    t2=time()
    print(t2-t1)
    原文作者:山药当人参
    原文地址: https://blog.51cto.com/14156081/2439975
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞