On this page
threading.Thread
Prev: threading.stack_size | Up: threading | Next: threading.ThreadError
Rel: threading.active_count, threading.Barrier, threading.BoundedSemaphore, threading.BrokenBarrierError
Ref: docs.python.org — threading.Thread
Tags: #public #python3 #stdlib #threading
Import
import threading
from threading import Thread
Signature & Overview
threading.Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None, context=None)
A class that represents a thread of control.
Methods & Attributes
Thread.daemon(...)— A boolean value indicating whether this thread is a daemon thread.Thread.getName(self)— Return a string used for identification purposes only.Thread.ident(...)— Thread identifier of this thread or None if it has not been started.Thread.isDaemon(self)— Return whether this thread is a daemon.Thread.is_alive(self)— Return whether the thread is alive.Thread.join(self, timeout=None)— Wait until the thread terminates.Thread.name(...)— A string used for identification purposes only.Thread.native_id(...)— Native integral thread ID of this thread, or None if it has not been started.Thread.run(self)— Method representing the thread's activity.Thread.setDaemon(self, daemonic)— Set whether this thread is a daemon.Thread.setName(self, name)— Set the name string for this thread.Thread.start(self)— Start the thread's activity.
Usage
import threading
results: list[int] = []
t = threading.Thread(target=lambda x: results.append(x * 2), args=(21,), name="doubler")
t.start()
t.join(timeout=2)
assert results == [42] and not t.is_alive()
Gotchas
- Always call
t.start(), nott.run(): Callingt.run()executes synchronously on the current thread. args=must be a tuple: For a single argument, writeargs=(21,)with a trailing comma—args=(21)raisesTypeError.- Prefer
concurrent.futures.ThreadPoolExecutorwhen you need return values or exception propagation.
REPL Inspect
from threading import Thread
help(Thread)
Linked from
Related notes
- tuts/python3/stdlib_module/threading/stack_size Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/ThreadError Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/active_count Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Barrier Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BoundedSemaphore Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BrokenBarrierError Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Condition shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/current_thread shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/enumerate shared tags: #stdlib, #threading