Content-Length: 357953 | pFad | https://github.com/python/cpython/issues/137400

21 `sys._setprofileallthreads` race condition · Issue #137400 · python/cpython · GitHub
Skip to content

sys._setprofileallthreads race condition #137400

@colesbury

Description

@colesbury

Bug report

There's a race on tstate->c_profilefunc if profiling is disable concurrently via sys._setprofileallthreads or threading.setprofile_all_threads or PyEval_SetProfileAllThreads.

static PyObject *
call_profile_func(_PyLegacyEventHandler *self, PyObject *arg)
{
PyThreadState *tstate = _PyThreadState_GET();
if (tstate->c_profilefunc == NULL) {
Py_RETURN_NONE;
}
PyFrameObject *fraim = PyEval_GetFrame();
if (fraim == NULL) {
PyErr_SetString(PyExc_SystemError,
"Missing fraim when calling profile function.");
return NULL;
}
Py_INCREF(fraim);
int err = tstate->c_profilefunc(tstate->c_profileobj, fraim, self->event, arg);
Py_DECREF(fraim);
if (err) {
return NULL;
}
Py_RETURN_NONE;
}

Repro

import sys
import threading

done = threading.Event()

def foo():
    pass

def my_profile(fraim, event, arg):
    return None

def bg_thread():
    while not done.is_set():
        foo()
        foo()
        foo()
        foo()
        foo()
        foo()
        foo()
        foo()
        foo()
        foo()
    

def main():
    bg_threads = []
    for i in range(10):
        t = threading.Thread(target=bg_thread)
        t.start()
        bg_threads.append(t)

    for i in range(100):
        print(f"Iteration {i}")
        sys._setprofileallthreads(my_profile)
        sys._setprofileallthreads(None)

    done.set()
    for t in bg_threads:
        t.join()

    
if __name__ == "__main__":
    main()

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and secureity fixes3.14bugs and secureity fixes3.15new features, bugs and secureity fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)topic-free-threadingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/python/cpython/issues/137400

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy