Python에서는 프로세스의 수를 Pool을 통해 관리할 수 있다.
APIs
apply(전달 함수, 파라미터)
apply_async(전달 함수, 파라미터): 프로세스를 비동기로 실행, 자원에 접근할 경우 프로세스가 종료되기를 기다림
map(전달 함수, 파라미터 리스트), map_async(전달 함수, 파라미터 리스트)
starmap(전달 함수, 여러 개 파라미터 리스트): 2차원 리스트 형태로 리스트 속 리스트에 여러 개의 파라미터를 전달할 수 있다.
return을 list 형식으로 하므로 get() 없이 바로 사용한다.
imap(전달 함수, 파라미터 리스트): iterator를 결과값으로 리턴한다. for문에 바로 사용할 수 있는 장점이 있다.
from multiprocessing import Pool
import multiprocessing as mp
import time
def mul(x, y):
c_prop = mp.current_process()
print("Running on Process", c_prop.name, "PID", c_prop.pid)
time.sleep(1)
print("Ended", x, '*', y, "Process", c_prop.name)
return x*y
def func(num):
c_prop = mp.current_process()
print("Running on Process", c_prop.name, "PID", c_prop.pid)
time.sleep(1)
print("Ended", num, "Process", c_prop.name)
return num
def callback_func(result):
print("callback_func got result: ", result)
if __name__ == "__main__":
p = Pool(3)
start = time.time()
# apply
ret1 = p.apply_async(func,(1,))
ret2 = p.apply_async(func,(2,))
ret3 = p.apply_async(func,(3,))
ret4 = p.apply_async(func,(4,))
ret5 = p.apply_async(func,(5,))
print(ret1.get(), ret2.get(), ret3.get(), ret4.get(), ret5.get())
# map
ret = p.map_async(func, [1,2,3,4,5], callback=callback_func)
print(ret.get())
# starmap
ret = p.starmap(mul, [[1,2],[2,3],[3,4],[4,5],[5,6]])
print(ret)
# imap
imap_iter = p.imap(func, [1,2,3,4,5])
for ret in imap_iter:
print("Got value", ret, "Time: ", time.time()-start)
delta_t = time.time()-start
print("Time :",delta_t)
p.close()
p.join()
Referenced: https://tempdev.tistory.com/27