1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from multiprocessing import Pool, Array
from functools import partial
import ctypes
import numpy as np
from time import sleep
import test
def heavy_duty_function(line):
"La fonction qu'on parallélise"
# On garde le CPU stupidement occupé...
# On peut vérifier le nombre de coeur qui travaillent.
c = 0
while c < 10**7:
c += 1
shared_array = from_array_to_np(test.shared_array_base)
print(shared_array[line])
def _initialize_subprocess(shared_array_base):
test.shared_array_base = shared_array_base
def list_of_list_to_array(data_type, data):
return Array(data_type, [elt for row in data for elt in row], lock=False)
def from_array_to_np(array):
shared_array = np.frombuffer(array, dtype=float)
return shared_array
if __name__=='__main__':
data = [[0,1,2,3],[4,5,6],[4,5,6,7,9]]
shared_array_base = list_of_list_to_array(ctypes.c_double, data)
with Pool(processes=4, initializer=_initialize_subprocess, initargs=(shared_array_base,)) as pool:
pool.map(heavy_duty_function, range(2))
shared_array = from_array_to_np(shared_array_base) |
Partager