Lesson 02
Function Threads
Start a Python child thread with threading.Thread, point it at a function, pass a tuple of arguments, and dispatch that function with start().
Start a Python child thread with threading.Thread, point it at a function, pass a tuple of arguments, and dispatch that function with start().
Example
import threading
def announce(m):
print(m, "on", threading.current_thread().name)
first = threading.Thread(target=announce, args=("Avery",), name="lane")
second = threading.Thread(target=announce, args=("Jordan",), name="hale")
first.start()
second.start()
first.join()
second.join()Both names print. On a desktop Python, the order of the two lines can vary because the children run as separate flows. args is a tuple, so one value is written ("Avery",) with the comma. The name attribute replaces the older setName method. Inside announce, current_thread().name is the child's name. The playground uses the same target, and if start() is refused it calls announce on MainThread.
Key takeaways
-
threading.Threadbuilds the child; it does not run the function yet -
targetis the function object, andargsis a tuple -
start()dispatches the child -
Read and write the name with the
nameattribute -
current_thread()tells you which flow is inside the function -
Next: Class Threads — pass a method as the target
-
Previous: Threads Overview
Loading playground…
Check your understanding
Function Threads Quiz
Which call actually begins the child thread's work?
1 / 10