Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-59705: Add _thread.set_name() function #127338

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

vstinner
Copy link
Member

@vstinner vstinner commented Nov 27, 2024

On Linux, threading.Thread now sets the thread name to the operating system.

configure now checks if pthread_setname_np() function is available.

On Linux, threading.Thread now sets the thread name to the operating
system.

configure now checks if pthread_setname_np() function is available.
@vstinner
Copy link
Member Author

This implementation is very basic on purpose. I plan to add support for more platform in follow-up PRs.

  • On Linux, set_name() does nothing if the name is longer than 15 bytes. Should the function truncate silently to 15 bytes instead? I don't think that raising an exception is very convenient here.
  • Setting Thread.name after Thread.start() doesn't call again set_name(). set_name() is called only once per thread, at startup.
  • I didn't add automated tests since I don't want to add a get_name() function (use Thread.name to get a thread name).

Demo 1 (main thread):

$ ./python
>>> import os
>>> pid=os.getpid()
>>> with open(f"/proc/{pid}/task/{pid}/comm") as fp: print(f"comm = {fp.read()!r}")
... 
comm = 'python\n'

>>> import _thread; _thread.set_name("demo")
>>> with open(f"/proc/{pid}/task/{pid}/comm") as fp: print(f"comm = {fp.read()!r}")
... 
comm = 'demo\n'

Demo 2 (thread):

$ ./python
>>> import threading, os, time
>>> os.getpid()
81921
>>> t=threading.Thread(target=time.sleep, args=(60,), name="sleeper")
>>> t.start()
^Z

$ cat /proc/81921/task/81927/comm 
sleeper

See also a previous attempt to implement the feature: #14578

@vstinner
Copy link
Member Author

I didn't add automated tests since I don't want to add a get_name() function (use Thread.name to get a thread name).

I changed my mind and added a private _thread._get_name() function for tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant