threading.Thread
- Python course
- Expert
- Lesson 31/47
- 5 min
Learn to create threads with threading.Thread.
What is threading.Thread?
threading.Thread starts a lightweight thread within the same process. Unlike processes, threads share memory; this makes communication easy but locking necessary.
You create a Thread by passing a function through target. t.start() launches the thread and t.join() waits for it to finish. It is very similar to Process; but since they share the same memory space data can be passed directly without a Queue. This is suitable for I/O-bound work.
Thread lifecycle
A Thread lifecycle resembles a Process: create, start, wait. You create with Thread(target=func), start with .start(), and wait with .join().
Because threads share memory they can access variables directly. But writing to the same resource at the same time causes a race condition; so you use a Lock. Without join the program may exit before the main thread finishes; calling join after start is a good habit.
Practice Call greet with Thread
Import with from threading import Thread. Define a greet function that does print("merhaba"). Create a thread with Thread(target=greet), run it with .start() and .join().
Starter code
# write the greet function
# create and run a threadSample solution
from threading import Thread
def greet():
print("merhaba")
t = Thread(target=greet)
t.start()
t.join()Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match Thread concepts
| Term | Meaning |
|---|---|
Thread |
Worker thread |
target |
Function |
start |
Launches |
join |
Waits |
2 What does Thread target take?
from threading import Thread
t = Thread(target=func)- The function to run Correct answer
- The thread ID
- A memory address
- A queue
Explanation: target takes the function the thread will run.
3 Complete the Thread definition
t = ____(target=greet)
t = Thread(target=greet)
Explanation: Thread(target=func) creates a new thread.