Skip to content

Make pysorteddict thread-safe #226

@tfpf

Description

@tfpf

This issue will serve as discovery to record what I need to change and what I don't need to to support the free-threaded build of Python 3.14.

  • import_supported_key_types need not lock anything

CPython holds a per-module lock during import. […] module initialization happens exactly once per interpreter in one C thread. […] you might set up a global static cache that is read-only after module initialization like this:

static int *cache = NULL;

PyMODINIT_FUNC
PyInit__module(void)
{
    PyObject *mod = PyModule_Create(&module);
    if (mod == NULL) {
        return NULL;
    }

    // don't need to lock or do anything special
    cache = setup_cache();

    // do rest of initialization
}

You can then read from cache at runtime in a context where you know the module is initialized without worrying about whether or not the per-module static cache is initialized.

Although the example is for single-phase initialisation, since initialisation is done only once, it is safe to conclude that static global read-only variables need not be locked before initialisation even when using multi-phase initialisation.

Updating Extension Modules - Python Free-Threading Guide

  • SortedDict::key_type should be initialised using a mutex lock before and after which it should be compared with nullptr

The first check serves as a way to avoid locking the mutex if the pointer is initialised. The second check serves to avoid setting the pointer to some other value if another initialised it already.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions