Multithreading in Python: Summary for
Interview
1 Basics of Multithreading
Definition: Multithreading is the ability of a CPU, or a single core in a multi-
core processor, to provide multiple threads of execution concurrently, supported
by the operating system.
Python Module: threading module is used for creating, controlling, and
managing threads.
2 Key Concepts
• Thread: The smallest unit of processing that can be scheduled by an
operating system.
• GIL (Global Interpreter Lock): A mutex that protects access to
Python objects, preventing multiple native threads from executing Python
bytecodes at once. This means that, in CPython, multithreading is not
ideal for CPU-bound tasks but can be effective for I/O-bound tasks.
3 Creating and Starting Threads
3.1 Creating a Thread
import threading
def thread_function ( name ):
print ( f " Thread { name } starting " )
thread = threading . Thread ( target = thread_function , args =(1 ,))
thread . start ()
1
3.2 Joining Threads
Ensures that the main program waits for threads to complete before continuing.
thread . join ()
4 Synchronization Primitives
4.1 Lock
Used to ensure that only one thread can access a resource at a time.
lock = threading . Lock ()
lock . acquire ()
try :
# Critical section
finally :
lock . release ()
4.2 RLock (Reentrant Lock)
A Lock that can be acquired multiple times by the same thread.
rlock = threading . RLock ()
4.3 Semaphore
Allows a fixed number of threads to access a resource.
semaphore = threading . Semaphore (3) # Allows up to 3 threads
4.4 Event
Used for signaling between threads.
event = threading . Event ()
event . set () # Signal event
event . wait () # Wait for event
4.5 Condition
Used for more complex synchronization scenarios.
2
condition = threading . Condition ()
with condition :
condition . wait () # Wait for a condition
condition . notify () # Notify one thread
condition . notify_all () # Notify all waiting threads