Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Doc/library/threading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ since it is impossible to detect the termination of alien threads.


.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, *, \
daemon=None, context=None)
daemon=None, context=None, start=False)

This constructor should always be called with keyword arguments. Arguments
are:
Expand Down Expand Up @@ -545,6 +545,8 @@ since it is impossible to detect the termination of alien threads.
current context, pass the value from :func:`~contextvars.copy_context`. The
flag defaults true on free-threaded builds and false otherwise.

If *start* is true, start immediately the thread after initialization.

If the subclass overrides the constructor, it must make sure to invoke the
base class constructor (``Thread.__init__()``) before doing anything else to
the thread.
Expand All @@ -558,6 +560,9 @@ since it is impossible to detect the termination of alien threads.
.. versionchanged:: 3.14
Added the *context* parameter.

.. versionchanged:: next
Added the *start* parameter.

.. method:: start()

Start the thread's activity.
Expand Down
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,13 @@ symtable
(Contributed by Serhiy Storchaka in :gh:`153844`.)


threading
---------

* Add *start* parameter to :class:`threading.Thread` to start immediately the
thread after initialization
(Contributed by Victor Stinner in :gh:`155334`.)

tkinter
-------

Expand Down
4 changes: 2 additions & 2 deletions Lib/concurrent/futures/thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,8 @@ def weakref_cb(_, q=self._work_queue):
t = threading.Thread(name=thread_name, target=_worker,
args=(weakref.ref(self, weakref_cb),
self._create_worker_context(),
self._work_queue))
t.start()
self._work_queue),
start=True)
self._threads.add(t)
_threads_queues[t] = self._work_queue

Expand Down
6 changes: 3 additions & 3 deletions Lib/concurrent/interpreters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,6 @@ def call_in_thread(self, callable, /, *args, **kwargs):

The return value and any raised exception are discarded.
"""
t = threading.Thread(target=self._call, args=(callable, args, kwargs))
t.start()
return t
return threading.Thread(target=self._call,
args=(callable, args, kwargs),
start=True)
2 changes: 1 addition & 1 deletion Lib/idlelib/pyshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ def __request_interrupt(self):
self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})

def interrupt_subprocess(self):
threading.Thread(target=self.__request_interrupt).start()
threading.Thread(target=self.__request_interrupt, start=True)

def kill_subprocess(self):
if self._afterid is not None:
Expand Down
2 changes: 1 addition & 1 deletion Lib/idlelib/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def main(del_exitfunc=False):
name='SockThread',
args=((LOCALHOST, port),),
daemon=True,
).start()
start=True)

while True:
try:
Expand Down
10 changes: 4 additions & 6 deletions Lib/multiprocessing/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,8 @@ def serve_forever(self):
self.stop_event = threading.Event()
process.current_process()._manager_server = self
try:
accepter = threading.Thread(target=self.accepter)
accepter.daemon = True
accepter.start()
accepter = threading.Thread(target=self.accepter,
daemon=True, start=True)
try:
while not self.stop_event.is_set():
self.stop_event.wait(1)
Expand All @@ -193,9 +192,8 @@ def accepter(self):
c = self.listener.accept()
except OSError:
continue
t = threading.Thread(target=self.handle_request, args=(c,))
t.daemon = True
t.start()
threading.Thread(target=self.handle_request, args=(c,),
daemon=True, start=True)

def _handle_request(self, c):
request = None
Expand Down
4 changes: 1 addition & 3 deletions Lib/multiprocessing/resource_sharer.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,7 @@ def _start(self):
util.debug('starting listener and thread for sending handles')
self._listener = Listener(authkey=process.current_process().authkey, backlog=128)
self._address = self._listener.address
t = threading.Thread(target=self._serve)
t.daemon = True
t.start()
t = threading.Thread(target=self._serve, daemon=True, start=True)
self._thread = t

def _serve(self):
Expand Down
2 changes: 1 addition & 1 deletion Lib/profiling/sampling/_child_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ def __enter__(self):
target=self._monitor_loop,
daemon=True,
name=f"child-monitor-{self.parent_pid}",
start=True,
)
self._monitor_thread.start()
return self

def __exit__(self, exc_type, exc_val, exc_tb):
Expand Down
3 changes: 1 addition & 2 deletions Lib/profiling/sampling/gecko_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,8 +749,7 @@ def spin():
sys.stderr.write('\r' + ' ' * (len(message) + 3) + '\r')
sys.stderr.flush()

spinner_thread = threading.Thread(target=spin, daemon=True)
spinner_thread.start()
spinner_thread = threading.Thread(target=spin, daemon=True, start=True)

temp_path = None
replaced = False
Expand Down
15 changes: 6 additions & 9 deletions Lib/subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -1792,26 +1792,23 @@ def _communicate(self, input, endtime, orig_timeout):
self._stdout_buff = []
self.stdout_thread = \
threading.Thread(target=self._readerthread,
args=(self.stdout, self._stdout_buff))
self.stdout_thread.daemon = True
self.stdout_thread.start()
args=(self.stdout, self._stdout_buff),
daemon=True, start=True)
if self.stderr and not hasattr(self, "_stderr_buff"):
self._stderr_buff = []
self.stderr_thread = \
threading.Thread(target=self._readerthread,
args=(self.stderr, self._stderr_buff))
self.stderr_thread.daemon = True
self.stderr_thread.start()
args=(self.stderr, self._stderr_buff),
daemon=True, start=True)

# Start writer thread to send input to stdin, unless already
# started. The thread writes input and closes stdin when done,
# or continues in the background on timeout.
if self.stdin and not hasattr(self, "_stdin_thread"):
self._stdin_thread = \
threading.Thread(target=self._writerthread,
args=(input,))
self._stdin_thread.daemon = True
self._stdin_thread.start()
args=(input,),
daemon=True, start=True)

# Wait for the writer thread, or time out. If we time out, the
# thread remains writing and the fd left open in case the user
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,15 @@ def run_in_bg():
self.assertEqual(err, b"")
self.assertEqual(out.strip(), b"Exiting...")

def test_threading_start(self):
# Test start=True parameter of Thread
def noop():
pass

t = threading.Thread(target=noop, start=True)
t.join()


class ThreadJoinOnShutdown(BaseTestCase):

def _run_and_join(self, script):
Expand Down
7 changes: 6 additions & 1 deletion Lib/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -1014,7 +1014,7 @@ class Thread:
_initialized = False

def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, *, daemon=None, context=None):
args=(), kwargs=None, *, daemon=None, context=None, start=False):
"""This constructor should always be called with keyword arguments. Arguments are:

*group* should be None; reserved for future extension when a ThreadGroup
Expand All @@ -1039,6 +1039,8 @@ class is implemented.
contextvars.Context(). To explicitly start with a copy of the current
context, pass the value from contextvars.copy_context().

If *start* is true, start immediately the thread after initialization.

If a subclass overrides the constructor, it must make sure to invoke
the base class constructor (Thread.__init__()) before doing anything
else to the thread.
Expand Down Expand Up @@ -1081,6 +1083,9 @@ class is implemented.
# For debugging and _after_fork()
_dangling.add(self)

if start:
self.start()

def _after_fork(self, new_ident=None):
# Private! Called by threading._after_fork().
self._started._at_fork_reinit()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add *start* parameter to :class:`threading.Thread` to start immediately the
thread after initialization. Patch by Victor Stinner.
Loading