Threading is a technique used in programming to allow multiple sequences of instructions (called threads) to run concurrently within a single process. It’s commonly used to perform tasks in parallel, improving the performance and responsiveness of applications—especially in programs that involve I/O operations (like file reading or network communication) or need to perform multiple tasks simultaneously.
🔹 What Is a Thread?
A thread is the smallest unit of execution in a program. Every program has at least one thread—the main thread. You can create additional threads to run parts of your code independently from the main thread.
🔹 Key Concepts in Threading
1. Process vs Thread
Feature | Process | Thread |
---|---|---|
Memory | Separate memory space | Shared memory space |
Communication | Inter-process communication | Shared memory, easier |
Overhead | High | Low |
Failure | Process failure won’t affect others | One thread crash may crash whole process |
2. Multithreading
Multithreading is the ability of a CPU or a single core in a multi-core processor to execute multiple threads concurrently.
Benefits:
- Efficient CPU utilization
- Faster execution for I/O-bound tasks
- Improved application responsiveness
Drawbacks:
- Complexity (race conditions, deadlocks)
- Not ideal for CPU-bound tasks in languages like Python (due to the GIL)
🔹 Threading in Programming Languages
Python (using threading
module):
pythonCopyEditimport threading
def print_numbers():
for i in range(5):
print(i)
# Create a thread
t = threading.Thread(target=print_numbers)
# Start thread
t.start()
# Wait for the thread to finish
t.join()
Java:
javaCopyEditclass MyThread extends Thread {
public void run() {
System.out.println("Running in a thread");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
🔹 Thread States
A thread typically moves through the following states:
- New: Thread is created but not started.
- Runnable: Ready to run, waiting for CPU time.
- Running: Currently executing.
- Blocked/Waiting: Waiting for resources or signal from another thread.
- Terminated: Execution is complete.
🔹 Common Threading Issues
- Race Condition
Multiple threads access shared data simultaneously leading to unpredictable results. - Deadlock
Two or more threads wait forever for resources locked by each other. - Starvation
A thread waits indefinitely due to high-priority threads occupying CPU. - Context Switching Overhead
Too many threads can lead to performance drop due to frequent switching.
🔹 Thread Safety
To avoid problems with concurrent access, use synchronization techniques:
- Locks (Mutexes)
- Semaphores
- Events
- Atomic operations
- Thread-safe data structures
