I wish to control the value in a given thread from another process. The following doesn't work since dproxy[i]
is a value rather a proxy. How should I be doing this?
import multiprocessing
import time
import threading
def g(d):
while d:
print(d)
time.sleep(1)
def f(dproxy):
for i in ("1","2"):
t = threading.Thread(target=g, args=(dproxy[i],))
t.daemon = True
t.start()
time.sleep(10)
manager = multiprocessing.Manager()
dproxy = manager.dict()
dproxy["1"] = "A"
dproxy["2"] = "B"
p = multiprocessing.Process(target=f, args=(dproxy,))
p.daemon = True
p.start()
time.sleep(2)
dproxy["1"] = "C"
time.sleep(2)
UPDATE
Second attempt that also doesn't work.
import multiprocessing
import time
import threading
def g(d):
while d:
print(d)
time.sleep(1)
def f(dproxy):
print(type(dproxy["1"]))
for i in ("1","2"):
t = threading.Thread(target=g, args=(dproxy[i],))
t.daemon = True
t.start()
time.sleep(10)
manager = multiprocessing.Manager()
dproxy = manager.dict()
dproxy["1"] = manager.Value("s","A")
dproxy["2"] = manager.Value("s","B")
p = multiprocessing.Process(target=f, args=(dproxy,))
p.daemon = True
p.start()
time.sleep(2)
dproxy["1"].set("C")
time.sleep(2)
you've got
t = threading.Thread(target=g, args=(dproxy[i],))
which will evaluate when creating the thread, so argument to your thread will be just your immutable string and that falls off from the manager
if you want to change it later you want to pass the your
dproxy
not an element of it.EDIT: Ok, so after looking into it bit more, it seems you are hitting a possible bug that prevents nested proxies to work correctly as it seems that as soon as you nest a proxy it gets 'de-proxied' and you end up with plain value.
In your second example however you can just change from
manager.dict()
to plaindict()
as you don't use it anyway it, but this will break if you actually try to modify thedict
itself but will work for thevalues
as they will arrive in your threads as proxy objects and will pick up the fact that they get modified using.set