New GitHub issue #110660 from ChristopherBrix:<br>
<hr>
<pre>
# Bug report
### Bug description:
When a `multiprocessing.Value` is passed to a new process without storing an external reference to it somewhere else, it gets garbage collected. This causes a bug: If the parent creates a new `multiprocessing.Value` objects and passes it to another process, both processes now share a memory location.
This code should deadlock, but it doesn't:
```python
import multiprocessing
import time
def inc_even(counter):
while True:
if counter.value % 2 == 0:
counter.value += 1
print("inc_even incremented counter")
else:
time.sleep(1)
def inc_odd(counter):
while True:
if counter.value % 2 == 1:
counter.value += 1
print("inc_odd incremented counter")
else:
time.sleep(1)
multiprocessing.Process(
target=inc_even,
kwargs={
"counter": multiprocessing.Value("i", 0),
},
).start()
multiprocessing.Process(
target=inc_odd,
kwargs={
"counter": multiprocessing.Value("i", 0),
},
).start()
```
Output:
```
inc_even incremented counter
inc_odd incremented counter
inc_even incremented counter
inc_odd incremented counter
...
```
Storing a reference to the counters in the parent process fixes this:
```
counterA = multiprocessing.Value("i", 0)
counterB = multiprocessing.Value("i", 0)
multiprocessing.Process(
target=inc_even,
kwargs={
"counter": counterA,
},
).start()
multiprocessing.Process(
target=inc_odd,
kwargs={
"counter": counterB,
},
).start()
```
Output:
```
inc_even incremented counter
```
This seems to happen because the reference is deleted: https://github.com/python/cpython/blob/v3.11.4/Lib/multiprocessing/process.py#L125
If this is not a bug but the intended behavior, the documentation needs to be updated: ["Explicitly pass resources to child processes"](https://docs.python.org/3/library/multiprocessing.html#programming-guidelines) currently states that the objects would not be garbage collected.
This bug report is a result of a [StackOverflow question](https://stackoverflow.com/questions/77269319/why-are-distinct-multiprocessing-value-objects-pointing-to-the-same-value/77269466).
### CPython versions tested on:
3.11
### Operating systems tested on:
Linux, macOS
</pre>
<hr>
<a href="https://github.com/python/cpython/issues/110660">View on GitHub</a>
<p>Labels: type-bug</p>
<p>Assignee: </p>