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 gregory.p.smith
Recipients gregory.p.smith
Date 2022-01-23.21:50:42
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1642974643.07.0.471616309157.issue46493@roundup.psfhosted.org>
In-reply-to
Content
It'd be handy to have a function to determine if there are multiple threads in the current process or not - at least on POSIXish systems.  This would be useful anytime a library is trying to use os.fork(), as fork() is not safe in a multi-threaded process.

Motivation: I want to _use_ this API to consider raising RuntimeWarnings in libraries that call fork() to highlight the problem to people attempting to use that code in multithreaded processes.

As POSIXy OSes don't usually have a simple API to get this information, one implementation such as this could make sense:

```
def is_process_multithreaded() -> bool:
    """Are there multiple threads in this process? OSError if no such OS API is available."""
    threads = 0
    ourself = str(os.gettid())
    i_feel_seen = False
    try:
        # Linux, NetBSD, any others?
        with os.scandir('/proc/self/task') as tasks:
            for task_dir_entry in tasks:
                # tid named subdirs should be the only thing that exists.
                # We do a simple conformity check just in case.
                if task_dir_entry.name.isdigit():
                    if task_dir_entry.name == ourself:
                        i_feel_seen = True
                    threads += 1
                    if i_feel_seen and threads > 1:
                        return True  # Multiple threads confirmed.
    except EnvironmentError:
        raise OSError('Unable to count threads on this platform.')
    if i_feel_seen and threads == 1:
        return False
    else:
        raise OSError(f'Unclear. Found {threads} in /proc/self/task and did not find ourself.')
```

macOS has mach darwin kernel APIs that can do this. Not well documented but they do work - https://stackoverflow.com/questions/21478229/how-to-count-number-of-alive-threads-in-ios

FreeBSD has APIs that can do this (see FreeBSD usr.bin/procstat/ source).

configure.ac checks and an extension module would be needed to integrate those.

My use case is not relevant to Windows (a platform unburdened by fork) but Windows APIs to answer the question exist if anyone has a reason to want this there as well - https://stackoverflow.com/questions/3749668/how-to-query-the-thread-count-of-a-process-using-the-regular-windows-c-c-apis
History
Date User Action Args
2022-01-23 21:50:43gregory.p.smithsetrecipients: + gregory.p.smith
2022-01-23 21:50:43gregory.p.smithsetmessageid: <1642974643.07.0.471616309157.issue46493@roundup.psfhosted.org>
2022-01-23 21:50:43gregory.p.smithlinkissue46493 messages
2022-01-23 21:50:42gregory.p.smithcreate