Junior — Middle
Explain the mechanism of threads in Python and where they can be applied.
sobes.tech AI
Answer from AI
In Python, threads are implemented through the threading module. A thread is a separate execution flow within a process, allowing multiple tasks to run in parallel.
However, due to the GIL (Global Interpreter Lock), only one Python code thread executes at a time in the standard CPython implementation, which limits parallelism in CPU-intensive tasks. Nevertheless, threads are useful for I/O-bound tasks (such as network requests, file operations), where the program can wait for an operation to complete and switch between threads.
Example of creating and starting a thread:
import threading
def worker():
print('Thread has started working')
thread = threading.Thread(target=worker)
thread.start()
thread.join()
Threads are used to improve application responsiveness, parallelize input/output processing, and implement concurrent tasks.