The `threading` module now sets the operating system thread name

Hi,

I modified the threading module to set the operating system thread name when spawning a thread.

Example on Linux:

$ ./python
>>> import threading, time
>>> thread=threading.Thread(target=time.sleep, args=(600,))
>>> thread.start()
>>> thread2=threading.Thread(target=time.sleep, args=(600,), name="worker")
>>> thread2.start()

The Tree View in htop displays the thread names “Thread-1 (sleep)” (thread) and “worker” (thread2):

htop

On Linux, a thread name is truncated to 15 bytes, so you don’t see the closing parenthesis of “Thread-1 (sleep)”.

Currently, the feature is supported on Linux, macOS, iOS, FreeBSD and Solaris. I plan to add Windows support. The code can be extended to support more operating systems.

Victor

17 Likes

I’ll add that it is partially supported on other platforms, but, if the name is longer than a platform specific limit, setting it does not have any effect instead of truncating it.

There may be other issues, so please test this feature, especially on non-mainstream platforms.

3 Likes