Skip to content

PyCriticalSection in Stable ABI #100

@encukou

Description

@encukou

After discussion, I propose that:
if we get a stable ABI for free-threading, we should add PyCriticalSection to the Stable ABI.

struct PyCriticalSection;   // 2 pointers; members are private
struct PyCriticalSection2;  // 3 pointers; members are private
int PyCriticalSection_BeginWithError(PyCriticalSection *sc, PyObject *obj);
void PyCriticalSection_End(PyCriticalSection *sc);
int PyCriticalSection2_BeginWithError(PyCriticalSection *sc, PyObject *o1, PyObject *o2);
void PyCriticalSection2_End(PyCriticalSection *sc);

The _BeginWithError functions need to be added to the non-limited API/ABI as well. They work like the existing PyCriticalSection_Begin, but return 0 on success and -1 with an exception set on failure.

The structs are meant to be heap-allocated, hence adding them to the ABI. Dynamic allocation would make the calls slow (7.283 vs. 3.93 ns in microbenchmarks).
If we ever need an incompatible change to the structs, all the related APIs need to be deprecated, and new API needs to be added.

In the existing API, the Begin functions are infallible and return void. I am not convinced they are special enough to break our “no infallible functions” rule. There's a strong argument for that though:

Lots of callers don’t handle error cases either because it’s inconvenient or impractical in the context of lock acquisition. We want to be able to add mutexes (or critical sections) to existing code without transforming functions or code paths that can’t fail into ones that can.

Hence the new names. I also want to mark the functions with ``[[nodiscard]]/attribute((warn_unused_result))` on compilers that support it, so that their users get a warning if the result is ignored.

I am proposing to not expose the macros (Py_BEGIN_CRITICAL_SECTION & co.) right now. With fallible functions, thy don't improve ergonomics much.

I'm also not proposing to PyMutex variants, as we don't have PyMutex in Stable ABI.

[vote cancelled; see another one below]

The Discourse discussion is still open in case you want to chime in.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions