Skip to content
PythonData, APIs, and Concurrencybeginner30 min read

Threading and Shared State

Understand Python threads, concurrency, race conditions, locks, events, and safe coordination between tasks.

In this lesson, you will learn

  • ✓Explain threads, concurrency, and the difference between concurrency and parallelism.
  • ✓Create, start, and join Python threads using the threading module.
  • ✓Explain shared mutable state and how race conditions can occur.
  • ✓Use threading.Lock to protect a shared resource.
  • ✓Use threading.Event to signal that a condition or task is complete.
  • ✓Recognize when threads are useful and understand the limitations of CPU-bound threading in standard CPython.

1. What are threads and concurrency?

A thread is an execution path within a process. A process can contain one or more threads. Threads in the same process share the process's memory, including references to objects, although each thread has its own execution state and call stack.

Concurrency means that multiple tasks can make progress during overlapping periods. Their instructions may be interleaved. Parallelism means that tasks execute at the same instant, for example on different CPU cores. Concurrent tasks are not necessarily running in parallel.

Threads are particularly useful for I/O-bound work. An I/O-bound task spends much of its time waiting for an operation such as a network response, file access, or socket communication. While one thread waits, another thread may be able to make progress.

Python provides the threading module. You create a Thread object by specifying the function it should execute, call start() to launch it, and call join() when you need to wait for it to finish.

Important: creating a Thread object does not start its function. Calling start() starts the thread. Calling the target function directly, such as work(), executes that function in the current thread instead.

Create, start, and join a thread

Create, start, and join a thread
python
import threading
 
def work():
print('Worker is running')
 
thread = threading.Thread(target=work)
print('Before start')
thread.start()
thread.join()
print('After join')
Output
Before start Worker is running After join

Importing threading makes Python's thread-related classes and functions available. Thread(target=work) creates a thread configured to call work. It does not execute work yet. The first print runs in the main thread before the worker starts. start() launches the worker thread. The worker prints its message. join() waits until the worker finishes. Therefore, the final message is printed after the worker's message. Because the worker has only one print statement and the main thread waits at join(), this example has a predictable output order.

Note

Thread scheduling is controlled by the runtime and operating system. Do not assume that a newly started thread always runs immediately. If multiple threads print messages without synchronization, their output order may vary.

2. Waiting for threads and understanding execution order

The main thread and a worker thread can make progress independently after start() is called. If the main thread needs a worker's result or needs to know that the worker has finished, join() provides a straightforward synchronization point.

A call to thread.join() blocks the calling thread until the specified thread terminates, unless a timeout is supplied. It does not terminate the worker. It also does not automatically return a value produced by the worker's function.

A worker function's return value is not returned by Thread.start() or Thread.join(). If you need to share a result, use an appropriate result container, a queue, a future from an executor, or another explicit communication mechanism.

Threads have lifecycle states. A newly created thread has not started. After start(), it may be running or waiting for execution. Once its target function finishes, it terminates. A thread can only be started once.

Use join() to establish a reliable order

Use join() to establish a reliable order
python
import threading
 
messages = []
 
def work():
messages.append('Task finished')
 
thread = threading.Thread(target=work)
thread.start()
thread.join()
print(messages)
Output
['Task finished']

The main thread creates an empty list and starts the worker. The worker appends one item to the list. The main thread waits at join(), so it does not print the list until the worker has terminated. The list contains the appended item when it is printed. This example demonstrates waiting for completion, not a general guarantee that all shared-list operations are safe in every concurrent design. More complex shared state may require explicit synchronization.

3. Shared state, race conditions, and locks

Shared state is data that multiple threads can access. Shared mutable state is especially important because multiple threads may try to modify the same object.

A race condition occurs when the correctness of a result depends on the timing or order of concurrent operations. For example, two threads may both read the same counter value before either writes the incremented value. One update can then overwrite the other.

An operation that looks like one simple statement is not necessarily an indivisible operation from the perspective of concurrent program logic. For example, counter += 1 conceptually reads a value, adds one, and stores the result. Concurrent updates must be designed so they cannot interfere incorrectly.

A threading.Lock provides mutual exclusion. A thread acquires the lock before entering a protected critical section and releases it when leaving. Only one thread at a time can hold that lock.

Use the with statement to manage a lock. The lock is released when the block exits, including when an exception occurs. Every thread that accesses the protected state must follow the same locking discipline; a lock cannot protect code that ignores it.

Do not use sleep() as a correctness mechanism. Delays can make a race condition easier to observe, but they do not guarantee a particular scheduling order and do not replace synchronization.

Protect a shared counter with Lock

Protect a shared counter with Lock
python
import threading
 
counter = 0
lock = threading.Lock()
 
def increment_many_times():
global counter
for _ in range(10_000):
with lock:
counter += 1
 
threads = [
threading.Thread(target=increment_many_times)
for _ in range(2)
]
 
for thread in threads:
thread.start()
 
for thread in threads:
thread.join()
 
print(counter)
Output
20000

Both workers update the same global counter. The global declaration tells Python that counter refers to the module-level variable rather than a new local variable. The lock ensures that only one worker at a time executes the counter update inside the critical section. Each worker performs 10,000 increments, so the total number of protected increments is 20,000. The start loop launches both workers. The join loop waits for both to finish. The final print therefore displays 20000. The lock protects the update; join() ensures the final read happens after both workers finish.

Caution

A lock only helps when every relevant access follows the same synchronization rule. Avoid holding a lock while performing slow network operations or waiting for unrelated work unless the design requires it. Long critical sections reduce concurrency and can contribute to deadlocks.

4. Communicate between threads with Event

Sometimes a thread needs to signal that something has happened, such as initialization finishing, a task becoming ready, or a shutdown request being issued. A threading.Event is designed for this kind of coordination.

An Event contains a flag that is initially clear. Calling set() turns the flag on. Calling is_set() checks the current flag. Calling wait() blocks until the flag is set, unless a timeout is reached.

The event flag stays set until clear() is called. An Event is useful when one or more threads need to wait for the same signal. It is not a counter: setting an event several times does not record several separate occurrences.

Use Event when you need to signal a condition. Use Lock when you need mutual exclusion around shared state. These tools solve different coordination problems and are not interchangeable.

Wait until a worker signals readiness

Wait until a worker signals readiness
python
import threading
 
ready = threading.Event()
 
def initialize():
print('Initializing')
ready.set()
 
def use_resource():
ready.wait()
print('Resource is ready')
 
worker = threading.Thread(target=initialize)
consumer = threading.Thread(target=use_resource)
 
consumer.start()
worker.start()
 
consumer.join()
worker.join()
Output
Initializing Resource is ready

Both threads are started, and the consumer may reach ready.wait() before initialization finishes. If the event flag is clear, wait() blocks the consumer. The initializer prints its message and calls ready.set(). The event releases the waiting consumer, which prints its message. The readiness signal establishes the required order between the two messages, regardless of which thread starts first. The joins ensure the main thread waits for both threads to finish.

Note

A timeout on Event.wait() lets a thread stop waiting after a specified duration, but the return value should be checked if your code must distinguish a signal from a timeout. A timeout does not automatically cancel the other thread.

5. When should you use threads?

Threads can improve responsiveness or overlap waiting time when a program performs multiple I/O-bound tasks. Examples include contacting multiple web services, reading from sockets, and waiting for file or device operations.

In standard CPython builds that use the Global Interpreter Lock (GIL), only one thread at a time can execute Python bytecode within an interpreter under the usual GIL-enabled execution model. This limits the ability of multiple threads to speed up CPU-bound pure-Python calculations.

The GIL does not mean threads are useless. I/O-bound threads can still be effective because the interpreter can switch to other threads while one waits for I/O. Some native extensions release the GIL while performing work. Python also has free-threaded builds, so the exact behavior depends on the interpreter build and libraries being used.

For CPU-bound work that needs to use multiple CPU cores, multiprocessing or an appropriate process pool may be a better choice. For large numbers of concurrent I/O tasks, threads, asynchronous programming with asyncio, or other concurrency tools may fit depending on the libraries and architecture.

Concurrency adds complexity. Start with a simple sequential implementation when it meets the requirement. Introduce threads when there is a clear reason, then explicitly design synchronization, error handling, and shutdown behavior.

Run two independent waiting tasks

Run two independent waiting tasks
python
import threading
import time
 
def task(label):
print(f'{label} started')
time.sleep(0.2) # Simulate waiting for I/O.
print(f'{label} finished')
 
first = threading.Thread(target=task, args=('A',))
second = threading.Thread(target=task, args=('B',))
 
first.start()
second.start()
 
first.join()
second.join()
print('All tasks finished')
Output
A started B started A finished B finished All tasks finished

The example uses sleep() only to simulate a task waiting; it is not intended to synchronize the threads. Both tasks can start before either task has finished waiting, allowing their waiting periods to overlap. The relative order of the A and B messages is not guaranteed in a general run. The displayed sequence is one possible output, not an exact-output guarantee. The final All tasks finished message is guaranteed to come after both worker threads terminate because the main thread joins each one. Real network and file operations have their own failure and timeout behavior. This example illustrates concurrency, not a production-ready I/O implementation.

Caution

Do not depend on thread scheduling to establish correctness. Use locks, events, queues, or other appropriate synchronization mechanisms. Also avoid creating an unlimited number of threads for unbounded work; excessive threads consume resources and can make a program slower or harder to manage.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Calling the target function instead of starting the thread.

Why it happens: Passing target=worker calls the function in the new thread; use target=worker without parentheses and call start() to run it in a separate thread.

Incorrect Approach
script.py
python
thread = threading.Thread(target=work)
thread.start()
thread.join()
Correct Solution
script.py
python
Pass the function itself as target=work, then call thread.start(). Writing target=work() calls the function immediately and passes its return value as the target instead.

Key takeaway: Pass the function itself as target=work, then call thread.start(). Writing target=work() calls the function immediately and passes its return value as the target instead.

#2 Assuming start() waits for the worker to finish.

Why it happens: start() schedules the thread to run, but it does not wait for completion; call join() when the caller must wait.

Incorrect Approach
script.py
python
thread.start()
thread.join()
print('Worker finished')
Correct Solution
script.py
python
start() launches the thread but does not wait for completion. Call join() when the current thread needs to wait.

Key takeaway: start() launches the thread but does not wait for completion. Call join() when the current thread needs to wait.

#3 Assuming thread output always appears in a fixed order.

Why it happens: Threads can be scheduled in different orders, so output order is not deterministic unless synchronization explicitly enforces it.

Incorrect Approach
script.py
python
event.wait()
print('The required condition has been signalled')
Correct Solution
script.py
python
Messages from different threads can interleave. Use explicit coordination when an order matters.

Key takeaway: Messages from different threads can interleave. Use explicit coordination when an order matters.

#4 Updating a shared counter without protecting a multi-step update.

Why it happens: A read-modify-write sequence on shared state can interleave between threads; protect the whole critical section with a lock or use thread-safe coordination.

Incorrect Approach
script.py
python
with lock:
counter += 1
Correct Solution
script.py
python
Use a lock around the critical section, or redesign the work to avoid shared mutable state.

Key takeaway: Use a lock around the critical section, or redesign the work to avoid shared mutable state.

#5 Thinking the GIL makes every shared-state design automatically safe.

Why it happens: The GIL does not make every multi-step operation atomic or remove logical races, especially when shared state and blocking operations are involved.

Incorrect Approach
script.py
python
with lock:
if account_balance >= amount:
account_balance -= amount
Correct Solution
script.py
python
The GIL is not a substitute for a synchronization design. Protect invariants and multi-step operations explicitly, and account for the interpreter build and native libraries.

Key takeaway: The GIL is not a substitute for a synchronization design. Protect invariants and multi-step operations explicitly, and account for the interpreter build and native libraries.

#6 Using sleep() to fix a race condition.

Why it happens: sleep() only changes timing and cannot guarantee correct synchronization; use locks, events, queues, or other coordination primitives.

Incorrect Approach
script.py
python
Using sleep() to fix a race condition.
Correct Solution
script.py
python
Sleeping changes timing but does not guarantee the necessary order. Use a Lock, Event, Queue, or another suitable synchronization primitive.

Key takeaway: Sleeping changes timing but does not guarantee the necessary order. Use a Lock, Event, Queue, or another suitable synchronization primitive.

#7 Expecting join() to return the worker's result.

Why it happens: join() waits for a thread to finish and returns None; communicate results through a shared result container, queue, or future-like abstraction.

Incorrect Approach
script.py
python
Expecting join() to return the worker's result.
Correct Solution
script.py
python
join() returns None after waiting. Use a thread-safe result channel, a shared result with appropriate coordination, or concurrent.futures when a return value is needed.

Key takeaway: join() returns None after waiting. Use a thread-safe result channel, a shared result with appropriate coordination, or concurrent.futures when a return value is needed.

#8 Holding a lock longer than necessary.

Why it happens: Holding a lock during unrelated work increases contention and can cause deadlocks; keep the critical section as short as correctness allows.

Incorrect Approach
script.py
python
Holding a lock longer than necessary.
Correct Solution
script.py
python
Keep critical sections focused on the state that must be protected. Avoid unrelated or slow work inside the lock when possible.

Key takeaway: Keep critical sections focused on the state that must be protected. Avoid unrelated or slow work inside the lock when possible.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a thread in Python?
Answer:
A thread is an execution path within a process. Threads in the same process share process memory, which makes communication convenient but means shared mutable state must be coordinated carefully.
Q2:What is the difference between concurrency and parallelism?
Answer:
Concurrency means multiple tasks can make progress during overlapping periods, potentially by interleaving their execution. Parallelism means tasks execute at the same time. A concurrent program is not necessarily parallel.
Q3:What is the difference between start() and join()?
Answer:
start() launches the thread's execution. join() blocks the calling thread until the specified thread terminates, unless a timeout expires. Neither method automatically retrieves the target function's return value.
Q4:What is a race condition, and how can you prevent one?
Answer:
A race condition occurs when the result depends on the timing or order of concurrent operations. Protect shared invariants with synchronization such as a Lock, or redesign the program to communicate through a thread-safe queue or avoid shared mutable state.
Q5:What is a critical section?
Answer:
A critical section is a region of code that accesses shared state and must obey a synchronization rule. A lock can provide mutual exclusion so only one thread at a time enters the protected section.
Q6:What is the difference between Lock and Event?
Answer:
A Lock provides mutual exclusion for protected operations. An Event communicates a signal through a flag that threads can set, inspect, or wait for. A lock protects a critical section; an event coordinates when a condition has been signalled.
Q7:Why are threads often useful for I/O-bound work?
Answer:
I/O-bound tasks spend time waiting for operations such as network responses. While one thread waits, another can make progress. This can improve responsiveness or overlap waiting time, although the actual performance gain depends on the workload.
Q8:Why may threads not speed up CPU-bound Python code in standard CPython?
Answer:
In standard GIL-enabled CPython, the Global Interpreter Lock limits simultaneous execution of Python bytecode within an interpreter. Multiprocessing may be a better choice for CPU-bound work that benefits from multiple CPU cores. The exact behavior depends on the Python build and any native libraries involved.
Q9:Does the GIL eliminate race conditions?
Answer:
No. The GIL is not a general guarantee that multi-step application operations preserve their intended invariants. Explicit synchronization is still needed when concurrent operations can interfere with shared state.
Q10:What happens if a worker thread raises an exception?
Answer:
An unhandled exception in a worker thread is normally reported through Python's thread exception handling, but it is not automatically re-raised in the main thread by join(). Programs that need to propagate worker failures should explicitly communicate exceptions or use a higher-level abstraction such as concurrent.futures.

Key takeaways

  • Use threading.Thread to define a worker, start() to launch it, and join() to wait for its termination.
  • Thread scheduling is not deterministic. Do not rely on timing or print order to establish correctness.
  • Shared mutable state can cause race conditions when concurrent operations interfere.
  • Use threading.Lock to protect critical sections and threading.Event to signal a condition or completion.
  • Threads are often helpful for I/O-bound tasks. CPU-bound performance depends on the interpreter build, workload, and available concurrency tools.
  • The GIL does not replace a sound synchronization design.
  • Keep critical sections small, handle worker failures deliberately, and test concurrent behavior rather than assuming one successful run proves correctness.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: