?print-pdf
' Created for
Process
конструктора.start()
методаjoin()
multiprocessing
модула са почти идентични с тези на threding
модула, което прави използването на Процеси в Python изключително лесно.
import multiprocessing as mp
import time
def worker(x):
pid = mp.current_process().name;
print("x = {} in {}".format(x, pid))
time.sleep(2)
if __name__ == '__main__':
# create the process
p = mp.Process(target=worker, args=(42,))
# start the process:
p.start()
# wait until process completes:
p.join()
print("Worker did its job as separate Process!")
if __name__ == '__main__':
, and not in a file which will be imported
import multiprocessing as mp
def increment(r):
global x
for _ in r:
x+=1
print(f"x in {mp.current_process().name}: {x}")
if __name__ == "__main__":
x = 0
pr1 = mp.Process(target=increment, args=(range(1000),))
pr2 = mp.Process(target=increment, args=(range(1000),))
pr1.start();pr2.start();
pr1.join();pr2.join();
print(f"x in {mp.current_process().name}: {x}")
#OUTPUT
# x in Process-1: 1000
# x in Process-2: 1000
# x in MainProcess: 0
Забележете, че всеки от процесите работи със собствено копие на x
, което не е свързано с x
в главния процес (главната програма).
queue
предлага FIFO структура, чрез класа queue.Queue()
import queue
queue = queue.Queue()
queue.put(1)
queue.put(2)
queue.put(3)
el1 = queue.get()
el2 = queue.get()
el3 = queue.get()
print(el1,el2,el3)
#OUTPUT
1 2 3
multiprocessing.Queue
има методи подобни на queue.Queue
класа но е оптимизиран за работа с процеси.
multiprocessing.Queue
са:put()
- за запис на данни в опашкатаget()
- за четене на данни от опашката
import multiprocessing as mp
def worker(q):
# get data from queue:
x = q.get()
x+=1
# save data to the queue
q.put(x)
print(f'x in {mp.current_process().name} = {x}')
if __name__ == '__main__':
# create a Queue object which will be shared among all processes
queue = mp.Queue()
# set the initial value for queue
queue.put(0)
processes = []
# crate and start 3 processes:
for _ in range(3):
pr = mp.Process(target=worker, args=(queue,))
pr.start()
processes.append(pr)
# wait for processes to end:
for pr in processes:
pr.join()
# get element from queue:
x = queue.get()
print(f'x in {mp.current_process().name} = {x}')
Забележете, че обекта queue
трябва да бъде споделен между процесите, които искат да имат достъп до тези данни.
from multiprocessing import Pool
import time
def worker(n):
# for light work, the pool is not efficient, try with n**10
return n**1000
if __name__ == '__main__':
t =time.time()
# create the Pool:
p = Pool(processes=5)
result = p.map(worker, range(100000))
p.close()
p.join()
print("Pool took: ", time.time() - t)
# serial processing:
t = time.time()
result = []
for x in range(100000):
result.append(worker(x))
# print("Result: ", result)
print("Serial processing took: ", time.time() - t)