Skip to content

Commit 16c0b7b

Browse files
Only destroy interpreters (by ID refcount) when created by the module.
1 parent b0b4ddb commit 16c0b7b

File tree

4 files changed

+18
-1
lines changed

4 files changed

+18
-1
lines changed

Include/cpython/pystate.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ typedef struct {
3030
(_PyMainInterpreterConfig){.install_signal_handlers = -1}
3131
/* Note: _PyMainInterpreterConfig_INIT sets other fields to 0/NULL */
3232

33+
PyAPI_FUNC(int) _PyInterpreterState_RequiresIDRef(PyInterpreterState *);
34+
PyAPI_FUNC(void) _PyInterpreterState_RequireIDRef(PyInterpreterState *, int);
35+
3336
PyAPI_FUNC(_PyCoreConfig *) _PyInterpreterState_GetCoreConfig(PyInterpreterState *);
3437
PyAPI_FUNC(_PyMainInterpreterConfig *) _PyInterpreterState_GetMainConfig(PyInterpreterState *);
3538

Include/internal/pycore_pystate.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ struct _is {
3030

3131
int64_t id;
3232
int64_t id_refcount;
33+
int requires_idref;
3334
PyThread_type_lock id_mutex;
3435

3536
int finalizing;

Modules/_xxsubinterpretersmodule.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1997,6 +1997,7 @@ interp_create(PyObject *self, PyObject *args)
19971997
PyThreadState_Swap(save_tstate);
19981998
return NULL;
19991999
}
2000+
_PyInterpreterState_RequireIDRef(tstate->interp, 1);
20002001
return idobj;
20012002
}
20022003

Python/pystate.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ _PyInterpreterState_IDDecref(PyInterpreterState *interp)
403403
int64_t refcount = interp->id_refcount;
404404
PyThread_release_lock(interp->id_mutex);
405405

406-
if (refcount == 0) {
406+
if (refcount == 0 && interp->requires_idref) {
407407
// XXX Using the "head" thread isn't strictly correct.
408408
PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
409409
// XXX Possible GILState issues?
@@ -413,6 +413,18 @@ _PyInterpreterState_IDDecref(PyInterpreterState *interp)
413413
}
414414
}
415415

416+
int
417+
_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
418+
{
419+
return interp->requires_idref;
420+
}
421+
422+
void
423+
_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
424+
{
425+
interp->requires_idref = required ? 1 : 0;
426+
}
427+
416428
_PyCoreConfig *
417429
_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
418430
{

0 commit comments

Comments
 (0)