Skip to content

Commit 92cf906

Browse files
committed
Implement weak references.
1 parent 5955de6 commit 92cf906

2 files changed

Lines changed: 31 additions & 5 deletions

File tree

Include/cpython/pystate.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ typedef struct _interpreter_weakref {
300300

301301
PyAPI_FUNC(PyInterpreterWeakRef) PyInterpreterWeakRef_Get(void);
302302
PyAPI_FUNC(PyInterpreterWeakRef) PyInterpreterWeakRef_Dup(PyInterpreterWeakRef wref);
303-
PyAPI_FUNC(PyInterpreterRef) PyInterpreterWeakRef_AsStrong(PyInterpreterWeakRef wref);
303+
PyAPI_FUNC(int) PyInterpreterWeakRef_AsStrong(PyInterpreterWeakRef wref, PyInterpreterRef *strong_ptr);
304304
PyAPI_FUNC(void) PyInterpreterWeakRef_Close(PyInterpreterWeakRef wref);
305305

306306
// Exports for '_testcapi' shared extension

Python/pystate.c

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3256,19 +3256,44 @@ PyInterpreterRef_Dup(PyInterpreterRef ref)
32563256
return (PyInterpreterRef)interp;
32573257
}
32583258

3259+
#undef PyInterpreterRef_Close
32593260
void
32603261
PyInterpreterRef_Close(PyInterpreterRef ref)
32613262
{
32623263
PyInterpreterState *interp = ref_as_interp(ref);
32633264
decref_interpreter(ref);
32643265
}
32653266

3266-
PyInterpreterState *
3267-
PyInterpreterState_Lookup(int64_t interp_id)
3267+
3268+
PyInterpreterWeakRef
3269+
PyInterpreterWeakRef_Get(void)
3270+
{
3271+
PyInterpreterState *interp = PyInterpreterState_Get();
3272+
PyInterpreterWeakRef wref = { interp->id };
3273+
return wref;
3274+
}
3275+
3276+
PyInterpreterWeakRef
3277+
PyInterpreterWeakRef_Dup(PyInterpreterWeakRef wref)
3278+
{
3279+
return wref;
3280+
}
3281+
3282+
void
3283+
PyInterpreterWeakRef_Close(PyInterpreterWeakRef wref)
3284+
{
3285+
return;
3286+
}
3287+
3288+
int
3289+
PyInterpreterWeakRef_AsStrong(PyInterpreterWeakRef wref, PyInterpreterRef *strong_ptr)
32683290
{
3291+
assert(strong_ptr != NULL);
3292+
int64_t interp_id = wref.id;
32693293
PyInterpreterState *interp = _PyInterpreterState_LookUpIDNoErr(interp_id);
32703294
if (interp == NULL) {
3271-
return NULL;
3295+
*strong_ptr = 0;
3296+
return -1;
32723297
}
32733298
HEAD_LOCK(&_PyRuntime); // Prevent deletion
32743299
struct _Py_finalizing_threads *finalizing = &interp->threads.finalizing;
@@ -3282,8 +3307,9 @@ PyInterpreterState_Lookup(int64_t interp_id)
32823307
}
32833308
PyMutex_Unlock(mutex);
32843309
HEAD_UNLOCK(&_PyRuntime);
3310+
*strong_ptr = (PyInterpreterRef)interp;
32853311

3286-
return interp;
3312+
return 0;
32873313
}
32883314

32893315
int

0 commit comments

Comments
 (0)