Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Update :c:func:`PyGC_Enable()`, :c:func:`PyGC_Disable()`,
:c:func:`PyGC_IsEnabled()` to use CAS operation for thread-safety at
free-threading build. Patch by Donghee Na.
18 changes: 9 additions & 9 deletions Python/gc_free_threading.c
Original file line number Diff line number Diff line change
Expand Up @@ -1476,7 +1476,8 @@ gc_should_collect(GCState *gcstate)
{
int count = _Py_atomic_load_int_relaxed(&gcstate->young.count);
int threshold = gcstate->young.threshold;
if (count <= threshold || threshold == 0 || !gcstate->enabled) {
int gc_enabled = _Py_atomic_load_int_relaxed(&gcstate->enabled);
if (count <= threshold || threshold == 0 || !gc_enabled) {
return false;
}
// Avoid quadratic behavior by scaling threshold to the number of live
Expand Down Expand Up @@ -1952,25 +1953,25 @@ int
PyGC_Enable(void)
{
GCState *gcstate = get_gc_state();
int old_state = gcstate->enabled;
gcstate->enabled = 1;
int old_state = _Py_atomic_load_int_relaxed(&gcstate->enabled);
while (!_Py_atomic_compare_exchange_int(&gcstate->enabled, &old_state, 1));
return old_state;
}

int
PyGC_Disable(void)
{
GCState *gcstate = get_gc_state();
int old_state = gcstate->enabled;
gcstate->enabled = 0;
int old_state = _Py_atomic_load_int_relaxed(&gcstate->enabled);
while (!_Py_atomic_compare_exchange_int(&gcstate->enabled, &old_state, 0));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to update old_state explicitly since __atomic_compare_exchange_n automatically handle.
https://gcc.gnu.org/onlinedocs/gcc-8.4.0/gcc/_005f_005fatomic-Builtins.html

return old_state;
}

int
PyGC_IsEnabled(void)
{
GCState *gcstate = get_gc_state();
return gcstate->enabled;
return _Py_atomic_load_int_relaxed(&gcstate->enabled);
}

/* Public API to invoke gc.collect() from C */
Expand All @@ -1980,7 +1981,7 @@ PyGC_Collect(void)
PyThreadState *tstate = _PyThreadState_GET();
GCState *gcstate = &tstate->interp->gc;

if (!gcstate->enabled) {
if (!_Py_atomic_load_int_relaxed(&gcstate->enabled)) {
return 0;
}

Expand Down Expand Up @@ -2139,8 +2140,7 @@ _PyObject_GC_Link(PyObject *op)
void
_Py_RunGC(PyThreadState *tstate)
{
GCState *gcstate = get_gc_state();
if (!gcstate->enabled) {
if (!PyGC_IsEnabled()) {
return;
}
gc_collect_main(tstate, 0, _Py_GC_REASON_HEAP);
Expand Down
Loading