#condfig:utf-8
import multiprocessing as mp
import threading as td
def job(a,d):
print('aaaaa')
t1 =td.Thread(target=job,args=(1,2))
p1 =mp.Process(target=job,args=(1,2))
t1.start()
p1.start()
t1.join()
p1.join()
#condfig:utf-8
import multiprocessing as mp
import threading as td
#定义一个被多线程调用的函数,q 就像一个队列,用来保存每次函数运行的结果
def job(q):
res = 0
for i in range(1000):
res+=i+i**2+i**3
q.put(res)
if __name__=='__main__':
q = mp.Queue()
p1 =mp.Process(target=job,args=(q,))
p2 = mp.Process(target=job,args=(q,))
#启动连接俩个现成
p1.start()
p2.start()
p1.join()
p2.join()
res1=q.get()
res2=q.get()
print(res1+res2)
对比下多进程 普通 多线程 那个运算块
#config:utf-8
#创建多进程
import threading as td
import multiprocessing as mp
def job(q):
res =0
for i in range(1000000):
res+= i+i**2+i**3
q.put(res)
def multicore():
q = mp.Queue()
p1=mp.Process(target=job,args =(q,))
p2=mp.Process(target=job,args=(q,))
p1.start()
p2.start()
p1.join()
p2.join()
res1=q.get()
res2=q.get()
print('多进程:',res1+res2)
#创建多线程
def multithread():
q = mp.Queue()
t1 = td.Thread(target=job,args=(q,))
t2 =td.Thread(target=job,args=(q,))
t1.start()
t2.start()
t1.join()
t2.join()
res1 = q.get()
res2 =q.get()
print('多线程:',res1+res2)
#创建普通函数
def normal():
res = 0
for _ in range(2):
for i in range(1000000):
res +=i+i**2+i**3
print('普通进程:',res)
#运行时间
import time
if __name__ == '__main__':
st =time.time()
normal()
st1 = time.time()
print('普通进程:',st1-st)
multithread()
st2 = time.time()
print('多线程:',st2-st1)
multicore()
print("多进程:",time.time()-st2)
最后 多进程 < 普通进程< 多线程