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
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
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
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.
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a thread in Python?
Q2:What is the difference between concurrency and parallelism?
Q3:What is the difference between start() and join()?
Q4:What is a race condition, and how can you prevent one?
Q5:What is a critical section?
Q6:What is the difference between Lock and Event?
Q7:Why are threads often useful for I/O-bound work?
Q8:Why may threads not speed up CPU-bound Python code in standard CPython?
Q9:Does the GIL eliminate race conditions?
Q10:What happens if a worker thread raises an exception?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: