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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
import multiprocessing as m
import pickle
#code "universelle"
class Store:
pass
class Shareable:
def __init__(self, size = 2**10):
object.__setattr__(self, 'store', m.Array('B', size))
o = Store() # This object will hold all shared values
s = pickle.dumps(o)
store(object.__getattribute__(self, 'store'), s)
def __getattr__(self, name):
s = load(object.__getattribute__(self, 'store'))
o = pickle.loads(s)
return getattr(o, name)
def __setattr__(self, name, value):
s = load(object.__getattribute__(self, 'store'))
o = pickle.loads(s)
setattr(o, name, value)
s = pickle.dumps(o)
store(object.__getattribute__(self, 'store'), s)
def store(arr, s):
for i, ch in enumerate(s):
arr[i] = ch
def load(arr):
l = arr[:]
return bytes(arr)
#tes objects ou structure a partager, voici un exemple
class Foo(Shareable):
def __init__(self):
super().__init__()
self.f = 1
self.f2 = 1
self.mylist=[0,1,2,3,4,5,6]
def foo(self):
self.f += 1
"""while True:
self.f2+=1"""
def Otherprocess(s):
print("Process2 :")
print(s.f)
s.mylist=[0]
"""while True:
s.f2+=1"""
if __name__ == '__main__':
import multiprocessing as m
import time
s = Foo()
print(s.f)
p = m.Process(target=s.foo, args=())
p.start()
#p.join()
p2 = m.Process(target=Otherprocess, args=(s,))
p2.start()
time.sleep(1)
print("Process1 :")
print(s.f)
print(s.mylist) |
Partager