进程池
Posted kuraki
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了进程池相关的知识,希望对你有一定的参考价值。
from multiprocessing import Pool,Process import time def func(n): for i in range(10): print(n+1) if __name__ == ‘__main__‘: st1 = time.time() pool = Pool(5) pool.map(func,range(100)) t1 = time.time() - st1 st2= time.time() p_lst = [] for i in range(100): p = Process(target=func,args=(i,)) p_lst.append(p) p.start() for p in p_lst: p.join() t2 = time.time() - st2 print(t1,t2)
import time,os from multiprocessing import Pool def func(n): print(‘start func%s‘%n,os.getpid()) time.sleep(1) print(‘end func%s‘%n,os.getpid()) if __name__ == ‘__main__‘: p = Pool(5) for i in range(20): p.apply_async(func,args=(i,)) p.close() p.join()
import socket from multiprocessing import Pool def func(conn): conn.send(b‘hello‘) print(conn.recv(1024).decode(‘utf-8‘)) conn.close() if __name__ ==‘__main__‘: sk = socket.socket() sk.bind((‘127.0.0.1‘,8080)) sk.listen() p = Pool(5) while True: conn,addr = sk.accept() p.apply_async(func,args=(conn,)) sk.close()
import socket sk = socket.socket() sk.connect((‘127.0.0.1‘,8080)) msg = sk.recv(1024).decode(‘utf-8‘) print(msg) msg2 = input(‘>>>‘).encode(‘utf-8‘) sk.send(msg2) sk.close()
from multiprocessing import Pool import time def func(i): time.sleep(0.5) return i*i if __name__ == ‘__main__‘: pool = Pool(5) res_l = [] for i in range(10): res = pool.apply_async(func,args=(i,)) res_l.append(res) for res in res_l:print(res.get())
from multiprocessing import Pool import time def func(i): time.sleep(0.5) return i*i if __name__ == ‘__main__‘: pool = Pool(5) ret = pool.map(func,range(10)) print(ret)
以上是关于进程池的主要内容,如果未能解决你的问题,请参考以下文章
在 Python 多处理进程中运行较慢的 OpenCV 代码片段