summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorVictor Stinner <vstinner@python.org>2024-12-10 16:33:11 (GMT)
committerGitHub <noreply@github.com>2024-12-10 16:33:11 (GMT)
commitc91ccbe4ac0ec15c503521f539b3528db85871b4 (patch)
treef96337c4bcde0b6832fc4d49c713261d680e1d9b /Lib
parent9af96f440618304e7cc609c246e1f8c8b2d7a119 (diff)
downloadcpython-c91ccbe4ac0ec15c503521f539b3528db85871b4.zip
cpython-c91ccbe4ac0ec15c503521f539b3528db85871b4.tar.gz
cpython-c91ccbe4ac0ec15c503521f539b3528db85871b4.tar.bz2
gh-59705: Set OS thread name when Thread.name is changed (#127702)
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_threading.py19
-rw-r--r--Lib/threading.py16
2 files changed, 30 insertions, 5 deletions
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index d05161f..3e164a1 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -2164,6 +2164,25 @@ class MiscTestCase(unittest.TestCase):
self.assertEqual(work_name, expected,
f"{len(work_name)=} and {len(expected)=}")
+ @unittest.skipUnless(hasattr(_thread, 'set_name'), "missing _thread.set_name")
+ @unittest.skipUnless(hasattr(_thread, '_get_name'), "missing _thread._get_name")
+ def test_change_name(self):
+ # Change the name of a thread while the thread is running
+
+ name1 = None
+ name2 = None
+ def work():
+ nonlocal name1, name2
+ name1 = _thread._get_name()
+ threading.current_thread().name = "new name"
+ name2 = _thread._get_name()
+
+ thread = threading.Thread(target=work, name="name")
+ thread.start()
+ thread.join()
+ self.assertEqual(name1, "name")
+ self.assertEqual(name2, "new name")
+
class InterruptMainTests(unittest.TestCase):
def check_interrupt_main_with_signal_handler(self, signum):
diff --git a/Lib/threading.py b/Lib/threading.py
index 3abd22a..78e5911 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -1026,16 +1026,20 @@ class Thread:
def _set_native_id(self):
self._native_id = get_native_id()
+ def _set_os_name(self):
+ if _set_name is None or not self._name:
+ return
+ try:
+ _set_name(self._name)
+ except OSError:
+ pass
+
def _bootstrap_inner(self):
try:
self._set_ident()
if _HAVE_THREAD_NATIVE_ID:
self._set_native_id()
- if _set_name is not None and self._name:
- try:
- _set_name(self._name)
- except OSError:
- pass
+ self._set_os_name()
self._started.set()
with _active_limbo_lock:
_active[self._ident] = self
@@ -1115,6 +1119,8 @@ class Thread:
def name(self, name):
assert self._initialized, "Thread.__init__() not called"
self._name = str(name)
+ if get_ident() == self._ident:
+ self._set_os_name()
@property
def ident(self):