CodeBlanks Logo Icon CodeBlanks

Summary - Threading and asyncio

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

main.py
# define counter and lock
# write the increment function
# run a thread and print

Sample solution

main.py
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

Question
from threading import Thread, ____
lock = Lock()
Answer
from threading import Thread, Lock
lock = Lock()

Explanation: Lock protects a critical section.

All lessons in Expert