Intern
What is single-threading?
sobes.tech AI
Answer from AI
Single-threading (or singletasking) is a program execution model where only one thread of instructions is executed at any given moment.
Main characteristics:
- Sequential execution: Code is executed line by line.
- Single call stack: Functions are called and return within the same stack.
- Lack of parallelism at the thread level: Different parts of code cannot be executed simultaneously in different CPU threads within a single process with one GIL (Global Interpreter Lock) in CPython.
Advantages:
- Simplicity: Easier to write and debug single-threaded code, as there are no data synchronization issues between threads.
- No race conditions: Since access to shared resources occurs from a single thread, there is no risk of concurrent data modification by multiple threads.
Disadvantages:
- Blocking operations: Long-running operations (e.g., input/output, network requests) block the entire program until they complete.
- Inefficient use of multi-core processors: The program uses only one CPU core.
- GUI applications may freeze: Long operations in the main thread can freeze the user interface.
Example:
// Single-threaded execution example
import time
def task1():
print("Task 1 started")
time.sleep(2) // Blocking operation
print("Task 1 completed")
def task2():
print("Task 2 started")
time.sleep(1) // Blocking operation
print("Task 2 completed")
print("Main program started")
task1() // task1 will complete first
task2() // then task2 will start
print("Main program finished")
In this example, task2 will only start after task1 has fully completed, despite task1 "sleeping" for 2 seconds.