Understanding concurrency is a key skill for Python developers, especially for those who are developing high-performance or network-based applications. Here’s a list of popular interview questions and answers related to Python concurrency:
1. What is Concurrency in Python?
Answer:
Concurrency in Python refers to the ability of a system to handle multiple tasks at the same time but not necessarily simultaneously. It allows multiple IO-bound or CPU-bound tasks to be executed more efficiently.
2. What is the Global Interpreter Lock (GIL) in Python?
Answer:
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects in the CPython interpreter. This means that even in a multi-threaded environment, only one thread can execute Python bytecodes at a time.
3. What is the difference between multi-threading and multi-processing?
Answer:
Multi-threading involves multiple threads of a single process, sharing the same memory space. Multi-processing involves multiple processes with their own memory space.
# Multi-threading
from threading import Thread
def print_numbers():
for i in range(10):
print(i)
thread = Thread(target=print_numbers)
thread.start()
# Multi-processing
from multiprocessing import Process
def print_numbers():
for i in range(10):
print(i)
process = Process(target=print_numbers)
process.start()
4. What is the asyncio
library?
Answer:asyncio
is a library in Python that provides an event loop and allows for asynchronous programming using async
and await
syntax.
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main())
5. How do you use a ThreadPoolExecutor?
Answer:
You can use ThreadPoolExecutor
from the concurrent.futures
module to execute functions in a pool of threads.
from concurrent.futures import ThreadPoolExecutor
def print_numbers(n):
for i in range(n):
print(i)
with ThreadPoolExecutor() as executor:
executor.submit(print_numbers, 10)
6. What is the queue
module in Python?
Answer:
The queue
module provides a way to create FIFO, LIFO, and priority queues, which are useful in multi-threading environments.
from queue import Queue
q = Queue()
q.put(1)
q.put(2)
print(q.get()) # Output: 1
7. How do you handle exceptions in threads?
Answer:
You can use the concurrent.futures.ThreadPoolExecutor
and its result()
method to catch exceptions.
from concurrent.futures import ThreadPoolExecutor
def raise_exception():
raise ValueError("An error occurred")
with ThreadPoolExecutor() as executor:
future = executor.submit(raise_exception)
try:
future.result()
except ValueError as e:
print(e)
8. What are semaphores?
Answer:
Semaphores are synchronization primitives that are used to control access to a shared resource.
from threading import Semaphore
sem = Semaphore()
with sem:
print("Critical section")
9. What is a deadlock?
Answer:
Deadlock is a situation in concurrent programming where two or more tasks are unable to proceed because they are each waiting for the other to release a lock.
10. How do you run a coroutine function in Python?
Answer:
Coroutine functions are defined using async def
and are run using an event loop provided by libraries like asyncio
.
import asyncio
async def hello_world():
print("Hello, world!")
asyncio.run(hello_world())
This should give you a good starting point for understanding Python concurrency.