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
33 changes: 33 additions & 0 deletions Doc/library/threading.rst
Comment thread
rqndom marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,39 @@ This module defines the following functions:
.. versionadded:: 3.4


.. function:: run([config, ]func, /, *args, **kwargs)
run_daemon([config, ]func, /, *args, **kwargs)

Run ``func(*args, **kwargs)`` in a thread and return the corresponding
:class:`Thread` object. The thread is started automatically.

*config* is an optional dict which can be used to pass additional
arguments to the :class:`Thread` constructor.

With :func:`run_daemon`, the thread is set as daemonic.

Example:

.. code-block:: python

import threading, urllib

def fetch(url, data=None):
response = urllib.request.urlopen(url, data)
# further processing...

t1 = threading.run(fetch, 'https://example.com/')
t2 = threading.run(fetch, 'https://example.com/post', data=payload)
t1.join()
t2.join()

# with configuration
t = threading.run({'name': 'http-worker'}, fetch, 'https://example.com/')
t.join()

.. versionadded:: next


.. function:: settrace(func)

.. index:: single: trace function
Expand Down
8 changes: 8 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,14 @@ symtable
(Contributed by Serhiy Storchaka in :gh:`153844`.)


threading
---------

* Add :func:`threading.run` and :func:`threading.run_daemon`
as a convenient way to start threads.
(Contributed by Romain Vavassori in :gh:`156131`.)


tkinter
-------

Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,34 @@ def run_in_bg():
self.assertEqual(err, b"")
self.assertEqual(out.strip(), b"Exiting...")

def test_run(self):
def func(x, y):
z.append(x + y)

z = []
thread = threading.run(func, 5, y=3)
thread.join()
self.assertEqual(z, [8])

z = []
thread = threading.run({'name': 'run-func'}, func, 5, y=3)
thread.join()
self.assertEqual(z, [8])
self.assertEqual(thread.name, 'run-func')

z = []
thread = threading.run_daemon(func, 8, y=4)
thread.join()
self.assertEqual(z, [12])
self.assertEqual(thread.daemon, True)

z = []
thread = threading.run_daemon({'name': 'run-func'}, func, 8, y=4)
thread.join()
self.assertEqual(z, [12])
self.assertEqual(thread.daemon, True)
self.assertEqual(thread.name, 'run-func')

class ThreadJoinOnShutdown(BaseTestCase):

def _run_and_join(self, script):
Expand Down
49 changes: 48 additions & 1 deletion Lib/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
'setprofile', 'settrace', 'local', 'stack_size',
'excepthook', 'ExceptHookArgs', 'gettrace', 'getprofile',
'serialize_iterator', 'synchronized_iterator', 'concurrent_tee',
'setprofile_all_threads','settrace_all_threads']
'setprofile_all_threads','settrace_all_threads',
'run', 'run_daemon']

# Rename some stuff so "from threading import *" is safe
_start_joinable_thread = _thread.start_joinable_thread
Expand Down Expand Up @@ -1664,6 +1665,52 @@ def enumerate():
with _active_limbo_lock:
return list(_active.values()) + list(_limbo.values())

def run(x, /, *args, **kwargs):
"""
run(func, /, *args, **kwargs) -> Thread object
run(config, func, /, *args, **kwargs) -> Thread object

Return a running thread of func(*args, **kwargs).

*config* is an optional dict which can be used to pass additional
arguments to the Thread constructor.

"""
if isinstance(x, dict):
if callable(x):
raise TypeError("ambiguous first argument: cannot determine if 'func' or 'config'")
if not args:
raise TypeError("missing positional argument 'func' after 'config'")

config = x
func, *args = args
else:
config = {}
func = x

thread = Thread(target=func, args=args, kwargs=kwargs, **config)
thread.start()
return thread

def run_daemon(x, /, *args, **kwargs):
"""
run_daemon(func, /, *args, **kwargs) -> Thread object
run_daemon(config, func, /, *args, **kwargs) -> Thread object

Return a running daemonic thread of func(*args, **kwargs).

*config* is an optional dict which can be used to pass additional
arguments to the Thread constructor.

"""
if isinstance(x, dict):
if callable(x):
raise TypeError("ambiguous first argument: cannot determine if 'func' or 'config'")

return run({'daemon': True} | x, *args, **kwargs)
else:
return run({'daemon': True}, x, *args, **kwargs)


_threading_atexits = []
_SHUTTING_DOWN = False
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add :func:`threading.run` and :func:`threading.run_daemon` functions as
a convenient way to start threads.
Loading