Junior — Middle
Explain the concept of threads of execution in Python programming language.
sobes.tech AI
Answer from AI
In Python, a thread is a separate sequence of instructions that can run concurrently with other threads within the same process.
Features of threads in Python:
- Threads are created using the
threadingmodule. - Due to the GIL (Global Interpreter Lock), only one thread executes Python code at a time in the standard CPython implementation, which limits parallelism in CPU-intensive tasks.
- Threads are useful for I/O-bound tasks, where the program can wait for a response and switch between threads.
Example of creating and starting a thread:
import threading
def worker():
print("Thread is running")
thread = threading.Thread(target=worker)
thread.start()
thread.join()
Thus, threads in Python allow for concurrent execution of code, but for true parallelism in computations, processes (multiprocessing) are often used.