This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients aldwinaldwin, asvetlov, docs@python, eric.snow, fabioz, int19h, ncoghlan, pitrou, tim.peters, vstinner
Date 2019-07-04.10:19:46
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1562235586.95.0.720729008203.issue31517@roundup.psfhosted.org>
In-reply-to
Content
Python internals already know who is the "main" thread: _PyRuntime.main_thread. It's maintained up to date, even after a fork, PyOS_AfterFork_Child() calls _PyRuntimeState_ReInitThreads() which does:

    // This was initially set in _PyRuntimeState_Init().
    runtime->main_thread = PyThread_get_thread_ident();

I already added _thread._is_main_interpreter() to deny spawning daemon threads in subinterpreters: bpo-37266.

We can add _thread._is_main_thread() which can reuse Modules/signalmodule.c code:

static int
is_main(_PyRuntimeState *runtime)
{
    unsigned long thread = PyThread_get_thread_ident();
    PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
    return (thread == runtime->main_thread
            && interp == runtime->interpreters.main);
}

For example, this function is used by signal.signal:

    if (!is_main(runtime)) {
        PyErr_SetString(PyExc_ValueError,
                        "signal only works in main thread");
        return NULL;
    }
History
Date User Action Args
2019-07-04 10:19:47vstinnersetrecipients: + vstinner, tim.peters, ncoghlan, pitrou, fabioz, asvetlov, docs@python, eric.snow, aldwinaldwin, int19h
2019-07-04 10:19:46vstinnersetmessageid: <1562235586.95.0.720729008203.issue31517@roundup.psfhosted.org>
2019-07-04 10:19:46vstinnerlinkissue31517 messages
2019-07-04 10:19:46vstinnercreate