Repository navigation
Description
Description of the issue
When using multiprocessing with the "spawn" method on Linux, processes sometimes fail to start with the message: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/_MEIOchafX/multiprocessing_bug.py' This happens if different threads try to launch processes concurrently. It would appear that the "spawn" method is not thread-safe when used with freeze support.
As mentioned below, this bug does not manifest when built with --onedir.
debug.log contains import and bootloader logging for a failure case.
Q: Does this happen with "fork"?
A: No
Q: Does this happen when running from source?
A: No, only when packaged as a pyinstaller executable with --onefile.
Q: Does this happen on Windows?
A: Unknown
Context information (for bug reports)
-
Output of
pyinstaller --version:5.7.0 -
Version of Python: Python 3.10.6
-
Platform: Ubuntu 22.04.1 LTS
-
How you installed Python: apt
-
Did you also try this on another platform?
- Ubuntu 18.04.6 LTS, pyinstaller 4.7, Python 3.7 - Bug is present
- WSL2 pyinstaller 4.7, Python 3.7 - Bug is present
-
try the latest development version, using the following command:
pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip- follow all the instructions in our "If Things Go Wrong" Guide
(https://github.com/pyinstaller/pyinstaller/wiki/If-Things-Go-Wrong) and
Make sure everything is packaged correctly
- start with clean installation
- use the latest development version
- Run your frozen program from a command window (shell) — instead of double-clicking on it
- Package your program in --onedir mode - BUG DOES NOT MANIFEST
- Package without UPX, say: use the option
--noupxor setupx=Falsein your .spec-file - - BUG DOES NOT MANIFEST - Repackage you application in verbose/debug mode. For this, pass the option
--debugtopyi-makespecorpyinstalleror useEXE(..., debug=1, ...)in your .spec file.
A minimal example program which shows the error
import multiprocessing
import sys
from threading import Thread
DEFAULT_N = 3
def main():
try:
n = int(sys.argv[1])
except IndexError:
n=DEFAULT_N
threads = []
for i in range(n):
threads.append(Thread(target=foo, args=(i, )))
for i in range(n):
threads[i].start()
for i in range(n):
threads[i].join()
def foo(i):
multiprocessing_context = multiprocessing.get_context(method="spawn")
q = multiprocessing_context.Queue()
p = multiprocessing_context.Process(target=bar, args=(q, i), daemon=True)
p.start()
p.join()
def bar(q, i):
q.put('hello')
print(f"{i} Added to queue")
if __name__ == "__main__":
multiprocessing.freeze_support()
main()Stacktrace / full error message
Note: If you can't reproduce the bug, try increasing the parameter from 2 to 5 (or higher).
$> dist/multiprocessing_bug 2
0 Added to queue
Traceback (most recent call last):
File "multiprocessing_bug.py", line 34, in <module>
multiprocessing.freeze_support()
File "PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py", line 49, in _freeze_support
File "multiprocessing/spawn.py", line 116, in spawn_main
File "multiprocessing/spawn.py", line 125, in _main
File "multiprocessing/spawn.py", line 236, in prepare
File "multiprocessing/spawn.py", line 287, in _fixup_main_from_path
File "runpy.py", line 288, in run_path
File "runpy.py", line 252, in _get_code_from_file
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/_MEIOchafX/multiprocessing_bug.py'
[8216] Failed to execute script 'multiprocessing_bug' due to unhandled exception!
Workaround
As shown below, adding a lock around the call to process.start() seems to resolve the issue.
import multiprocessing
import sys
from threading import Thread, Lock
DEFAULT_N = 3
def main():
try:
n = int(sys.argv[1])
except IndexError:
n=DEFAULT_N
threads = []
for i in range(n):
threads.append(Thread(target=foo, args=(i, )))
for i in range(n):
threads[i].start()
for i in range(n):
threads[i].join()
lock = Lock()
def foo(i):
multiprocessing_context = multiprocessing.get_context(method="spawn")
q = multiprocessing_context.Queue()
p = multiprocessing_context.Process(target=bar, args=(q, i), daemon=True)
with lock:
p.start()
p.join()
def bar(q, i):
q.put('hello')
print(f"{i} Added to queue")
if __name__ == "__main__":
multiprocessing.freeze_support()
main()
Activity
Agent: Fix multiprocessing race condition with "spawn" and pyinstaller
Agent: Fix multiprocessing race condition with "spawn" and pyinstaller
rokm commentedon Feb 1, 2023
Thanks for preliminary analysis and reproducer!
The problem is indeed lack of thread-safety in our
multiprocesssupport. Specifically,putenv/unsetenvcalls fromFrozenSupportMixIn,pyinstaller/PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py
Lines 66 to 80 in d6ff080
affect the global state and when multiple instances are created (multiple processes are spawned from different threads), they end up racing each other. E.g., the 2nd process' instance sets the environment variable, only for it to be cleared by the 1st process' instance - therefore, the 2nd process ends up unpacking itself into different temporary location, leading to filename/path mismatch during lookup.
I don't think we have any other way of passing custom environment to
multiprocessing.popen_*.Popen, so we'll probably need to resort to a class-wideLockto force serialization of those environment modifications.Agent: Fix multiprocessing race condition with "spawn" and pyinstaller
VakarisZ commentedon Feb 2, 2023
BTW this doesn't happen on windows