30 lines
1.0 KiB
Python
30 lines
1.0 KiB
Python
# Multiprocessing: Sharing data between processes (a Value or Array memory share must be created as processes do not share data by default)
|
|
from multiprocessing import Process, Value, Array, Lock
|
|
from multiprocessing import Queue
|
|
import os
|
|
import time
|
|
|
|
def add_100(numbers, lock, queue):
|
|
for _ in range(100):
|
|
time.sleep(0.01)
|
|
for i in range(len(numbers)):
|
|
with lock:
|
|
numbers[i] += 1
|
|
queue.put(list(numbers))
|
|
print(f'Process {os.getpid()} has finished execution.')
|
|
|
|
if __name__ == "__main__":
|
|
lock = Lock()
|
|
shared_array = Array('d', [0.0, 100.0, 200.0, 300.0, 400.0])
|
|
queue = Queue()
|
|
|
|
print('Array at the beginning is: ', list(shared_array))
|
|
p1 = Process(target=add_100, args=(shared_array, lock, queue))
|
|
p2 = Process(target=add_100, args=(shared_array, lock, queue))
|
|
p1.start()
|
|
p2.start()
|
|
p1.join()
|
|
p2.join()
|
|
print('Array at the end is: ', list(shared_array))
|
|
while not queue.empty():
|
|
print('Process output: ', queue.get()) |