25 lines
856 B
Python
25 lines
856 B
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
|
|
import os
|
|
import time
|
|
|
|
def add_100(numbers, lock):
|
|
for _ in range(100):
|
|
time.sleep(0.01)
|
|
for i in range(len(numbers)):
|
|
with lock:
|
|
numbers[i] += 1
|
|
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])
|
|
|
|
print('Array at the beginning is: ', list(shared_array))
|
|
p1 = Process(target=add_100, args=(shared_array, lock))
|
|
p2 = Process(target=add_100, args=(shared_array, lock))
|
|
p1.start()
|
|
p2.start()
|
|
p1.join()
|
|
p2.join()
|
|
print('Array at the end is: ', list(shared_array)) |