Summary - Threading and asyncio
- Python course
- Expert
- Lesson 36/47
- 5 min
Combine Thread, Lock and ThreadPoolExecutor to write a counter.
Recap: Threading and asyncio
In this group you learned threaded and concurrent programming. You started threads with Thread and protected critical sections with Lock.
You saw how the GIL blocks CPU-bound work. You used a pool with ThreadPoolExecutor. You learned the single-threaded alternative asyncio. Now you will combine these into a threaded counter: a safe counter with Thread and Lock.
Practice Write a threaded counter
Import with from threading import Thread, Lock. Define count = 0 and lock = Lock(). Write an increment function: global count, lock.acquire(), count += 1, lock.release(). Create a thread with Thread(target=increment), call .start() and .join(). Print count.
Starter code
# define counter and lock
# write the increment function
# run a thread and printSample solution
from threading import Thread, Lock
count = 0
lock = Lock()
def increment():
global count
lock.acquire()
count += 1
lock.release()
t = Thread(target=increment)
t.start()
t.join()
print(count)Expected output
1
What you learned
In this group you learned two approaches to concurrent programming in Python. You saw threads with threading and critical section protection with Lock.
You understood how the GIL blocks parallelism for CPU-bound work. You learned pool management with ThreadPoolExecutor. You saw the single-threaded concurrent alternative asyncio. In the summary you combined Thread and Lock into a safe counter.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match all threading concepts
| Term | Meaning |
|---|---|
Thread |
Worker thread |
Lock |
Critical section |
GIL |
Parallelism barrier |
asyncio |
Concurrent I/O |
2 Which tool for which job?
- ThreadPoolExecutor for a pool Correct answer
- Lock to start a thread
- Thread to protect a critical section
- GIL for parallel speedup
Explanation: answer: ThreadPoolExecutor for a pool. Lock protects, Thread starts, GIL blocks.
3 Final blank
from threading import Thread, ____
lock = Lock()
from threading import Thread, Lock
lock = Lock()
Explanation: Lock protects a critical section.