Skip to content

Commit 2d438fc

Browse files
bpo-37421: Fix multiprocessing get_temp_dir() finalizer (GH-14572)
Fix multiprocessing.util.get_temp_dir() finalizer: clear also the 'tempdir' configuration of the current process, so next call to get_temp_dir() will create a new temporary directory, rather than reusing the removed temporary directory. (cherry picked from commit 9d40554) Co-authored-by: Victor Stinner <vstinner@redhat.com>
1 parent d7d9c9f commit 2d438fc

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

Lib/multiprocessing/util.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,14 +106,26 @@ def log_to_stderr(level=None):
106106
# Function returning a temp directory which will be removed on exit
107107
#
108108

109+
def _remove_temp_dir(rmtree, tempdir):
110+
rmtree(tempdir)
111+
112+
current_process = process.current_process()
113+
# current_process() can be None if the finalizer is called
114+
# late during Python finalization
115+
if current_process is not None:
116+
current_process._config['tempdir'] = None
117+
109118
def get_temp_dir():
110119
# get name of a temp directory which will be automatically cleaned up
111120
tempdir = process.current_process()._config.get('tempdir')
112121
if tempdir is None:
113122
import shutil, tempfile
114123
tempdir = tempfile.mkdtemp(prefix='pymp-')
115124
info('created temp directory %s', tempdir)
116-
Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100)
125+
# keep a strong reference to shutil.rmtree(), since the finalizer
126+
# can be called late during Python shutdown
127+
Finalize(None, _remove_temp_dir, args=(shutil.rmtree, tempdir),
128+
exitpriority=-100)
117129
process.current_process()._config['tempdir'] = tempdir
118130
return tempdir
119131

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :func:`multiprocessing.util.get_temp_dir` finalizer: clear also the
2+
'tempdir' configuration of the current process, so next call to
3+
``get_temp_dir()`` will create a new temporary directory, rather than
4+
reusing the removed temporary directory.

0 commit comments

Comments
 (0)