GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — bpo-41833: threading.Thread now uses the target name by vstinner · Pull Request #22357 · python/cpython

bpo-41833: threading.Thread now uses the target name #22357

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.

Sign up for GitHub

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

Merged
vstinner merged 3 commits into python:master from vstinner:thread_name
Sep 23, 2020

Uh oh!

There was an error while loading. Please reload this page.

Merged

bpo-41833: threading.Thread now uses the target name #22357

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
8b4397d
bpo-41833: threading.Thread now uses the target name
vstinner Sep 22, 2020
51b15fb
Avoid formatting errors
vstinner Sep 23, 2020
859b4c2
Allow to set the name to an empty string
vstinner Sep 23, 2020
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

9 changes: 7 additions & 2 deletions 9 Doc/library/threading.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,10 @@ since it is impossible to detect the termination of alien threads.
*target* is the callable object to be invoked by the :meth:`run` method.
Defaults to ``None``, meaning nothing is called.

*name* is the thread name. By default, a unique name is constructed of the
form "Thread-*N*" where *N* is a small decimal number.
*name* is the thread name. By default, a unique name is constructed
of the form "Thread-*N*" where *N* is a small decimal number,
or "Thread-*N* (target)" where "target" is ``target.__name__`` if the
*target* argument is specified.

*args* is the argument tuple for the target invocation. Defaults to ``()``.

Expand All @@ -280,6 +282,9 @@ since it is impossible to detect the termination of alien threads.
base class constructor (``Thread.__init__()``) before doing anything else to
the thread.

.. versionchanged:: 3.10
Use the *target* name if *name* argument is omitted.

.. versionchanged:: 3.3
Added the *daemon* argument.

Expand Down
34 changes: 31 additions & 3 deletions 34 Lib/test/test_threading.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import signal
import textwrap

from unittest import mock
from test import lock_tests
from test import support

Expand Down Expand Up @@ -86,6 +87,33 @@ def tearDown(self):

class ThreadTests(BaseTestCase):

@cpython_only
Comment thread
vstinner marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

def test_name(self):
def func(): pass

thread = threading.Thread(name="myname1")
self.assertEqual(thread.name, "myname1")

# Convert int name to str
thread = threading.Thread(name=123)
self.assertEqual(thread.name, "123")

# target name is ignored if name is specified
thread = threading.Thread(target=func, name="myname2")
self.assertEqual(thread.name, "myname2")

with mock.patch.object(threading, '_counter', return_value=2):
thread = threading.Thread(name="")
self.assertEqual(thread.name, "Thread-2")

with mock.patch.object(threading, '_counter', return_value=3):
thread = threading.Thread()
self.assertEqual(thread.name, "Thread-3")

with mock.patch.object(threading, '_counter', return_value=5):
thread = threading.Thread(target=func)
self.assertEqual(thread.name, "Thread-5 (func)")

# Create a bunch of threads, let each do some work, wait until all are
# done.
def test_various_ops(self):
Expand Down Expand Up @@ -531,7 +559,7 @@ def test_main_thread_after_fork_from_nonmain_thread(self):
import os, threading, sys
from test import support

def f():
def func():
pid = os.fork()
if pid == 0:
main = threading.main_thread()
Expand All @@ -544,14 +572,14 @@ def f():
else:
support.wait_process(pid, exitcode=0)

th = threading.Thread(target=f)
th = threading.Thread(target=func)
th.start()
th.join()
"""
_, out, err = assert_python_ok("-c", code)
data = out.decode().replace('\r', '')
self.assertEqual(err, b"")
self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")

def test_main_thread_during_shutdown(self):
# bpo-31516: current_thread() should still point to the main thread
Expand Down
20 changes: 15 additions & 5 deletions 20 Lib/threading.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -745,10 +745,9 @@ class BrokenBarrierError(RuntimeError):


# Helper to generate new thread names
_counter = _count().__next__
_counter() # Consume 0 so first non-main thread has id 1.
def _newname(template="Thread-%d"):
return template % _counter()
_counter = _count(1).__next__
def _newname(name_template):
return name_template % _counter()

# Active thread administration
_active_limbo_lock = _allocate_lock()
Expand Down Expand Up @@ -800,8 +799,19 @@ class is implemented.
assert group is None, "group argument must be None for now"
if kwargs is None:
kwargs = {}
if name:
name = str(name)
else:
name = _newname("Thread-%d")
if target is not None:
try:
target_name = target.__name__
name += f" ({target_name})"
except AttributeError:
pass

self._target = target
self._name = str(name or _newname())
self._name = name
self._args = args
self._kwargs = kwargs
if daemon is not None:
Expand Down
2 changes: 2 additions & 0 deletions 2 Misc/NEWS.d/next/Library/2020-09-22-13-51-14.bpo-41833.6HVDjT.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
The :class:`threading.Thread` constructor now uses the target name if the
*target* argument is specified but the *name* argument is omitted.
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.