Skip to content

Conversation

@kumaraditya303
Copy link
Contributor

@kumaraditya303 kumaraditya303 commented Dec 22, 2025

@kumaraditya303 kumaraditya303 requested a review from 1st1 as a code owner December 22, 2025 16:18
@kumaraditya303 kumaraditya303 changed the title gh-116738: make entering of context thread safe gh-116738: make entering of contextvars.Context thread safe Dec 22, 2025
Python/context.c Outdated
Comment on lines 232 to 237
#ifdef Py_GIL_DISABLED
int already_entered = _Py_atomic_exchange_int(&ctx->ctx_entered, 0);
#else
int already_entered = ctx->ctx_entered;
ctx->ctx_entered = 0;
#endif
Copy link
Contributor

Choose a reason for hiding this comment

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

ctx->ctx_entered functions like a lock. So I think I'd write this as:

    int already_entered = FT_ATOMIC_LOAD_INT_RELAXED(ctx->ctx_entered);
    if (!already_entered) {
        ...
    }
    if (ts->context != (PyObject *)ctx) {
        ...
    }
    FT_ATOMIC_STORE_INT_RELEASE(ctx->ctx_entered, 0);

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks! I used FT_ATOMIC_STORE_INT as there is no FT_ATOMIC_STORE_INT_RELEASE and I don't think using seq-cst over release would hurt performance here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants