Python Multithreading & Concurrency MCQs

1 min read

Python multithreading is a core concurrency feature that enables execution of multiple threads within a single process to handle concurrent tasks efficient in I/O-bound operations. Standard CPython implements the Global Interpreter Lock (GIL), a mutex that ensures only one native thread executes Python bytecode at a time, limiting standard multithreading gains on CPU-bound operations. The built-in threading module provides standard primitives including Thread, Lock, RLock, Semaphore, and Event to manage execution lifecycles and synchronize shared memory safely. Modern applications often pair multithreading with concurrent.futures.ThreadPoolExecutor or queue.Queue to build scalable background pipelines without data races or deadlocks. Mastering Python multithreading and concurrency concepts is crucial for backend engineering, high-throughput network programming, and technical technical interview preparation.

1. What is the primary purpose of the Global Interpreter Lock (GIL) in CPython?

a) To ensure thread safety for Python's memory management by preventing multiple native threads from executing Python bytecodes at once.
b) To allow maximum parallel execution of CPU-bound tasks across multi-core processors using threads.
c) To automatically optimize thread scheduling priority for high-performance network sockets.
d) To eliminate the need for synchronization primitives like locks and semaphores.
Correct Answer: a) To ensure thread safety for Python's memory management by preventing multiple native threads from executing Python bytecodes at once.
Explanation:
The GIL protects CPython's internal memory structures (like reference counting) from race conditions, but it prevents multiple threads from executing Python bytecode simultaneously on separate CPU cores.

2. Which type of task benefits the most from Python's threading module despite the presence of the GIL?

a) CPU-bound tasks such as heavy mathematical calculations and image rendering.
b) I/O-bound tasks such as network requests, file reading/writing, and database queries.
c) Memory-bound tasks requiring continuous cache invalidation.
d) Algorithm optimization tasks running purely in RAM.
Correct Answer: b) I/O-bound tasks such as network requests, file reading/writing, and database queries.
Explanation:
During I/O operations, Python threads release the GIL while waiting for responses, allowing other threads to run and make efficient use of idle time.

3. Which synchronization primitive in Python's threading module ensures that only one thread can access a critical section of code at a time?

a) Event
b) Semaphore
c) Lock
d) Barrier
Correct Answer: c) Lock
Explanation:
A Lock (mutex) has two states: locked and unlocked. When a thread acquires it, any other thread attempting to acquire it will block until it is released.

4. What is the primary advantage of the multiprocessing module over the threading module in Python?

a) Processes share memory space natively, making communication faster than threads.
b) Processes bypass the Global Interpreter Lock (GIL) by utilizing separate memory spaces, enabling true parallel execution on multi-core CPUs.
c) Processes consume significantly fewer system resources than threads.
d) Processes do not require any inter-process communication mechanisms.
Correct Answer: b) Processes bypass the Global Interpreter Lock (GIL) by utilizing separate memory spaces, enabling true parallel execution on multi-core CPUs.
Explanation:
Because each process runs in its own Python interpreter instance with its own memory space, CPU-bound tasks can truly execute in parallel across multiple CPU cores.

5. What does the concurrent.futures.ThreadPoolExecutor primarily manage?

a) A pool of worker operating system processes for CPU-heavy tasks.
b) A pool of worker threads to execute asynchronous callables concurrently.
c) Asynchronous event loops for coroutines.
d) Low-level TCP network socket multiplexing.
Correct Answer: b) A pool of worker threads to execute asynchronous callables concurrently.
Explanation:
ThreadPoolExecutor provides a high-level API for asynchronously executing callables using a pool of reusable threads.

6. What is a deadlock in concurrent programming?

a) When a thread finishes execution faster than expected.
b) A situation where two or more threads are blocked indefinitely, each waiting for resources held by the other.
c) When the CPU cache becomes completely full during threading operations.
d) An error raised when a thread attempts to release a lock it does not own.
Correct Answer: b) A situation where two or more threads are blocked indefinitely, each waiting for resources held by the other.
Explanation:
Deadlocks occur due to circular dependencies on synchronization locks, causing programs to freeze permanently.

7. Which class is used in Python's threading module to allow multiple threads to wait until a specific condition is met?

a) Condition
b) Timer
c) Queue
d) Local
Correct Answer: a) Condition
Explanation:
A Condition variable allows one or more threads to wait until notified by another thread that a particular state change has occurred.

8. What is the primary difference between Queue.Queue and collections.deque in a multi-threaded environment?

a) collections.deque is thread-safe for all operations, whereas Queue.Queue is not.
b) Queue.Queue is fully thread-safe with built-in locking primitives, whereas collections.deque operations are not globally thread-safe for multi-step mutations.
c) Queue.Queue can only store integers, while deque can store any object.
d) There is no functional difference in concurrency safety.
Correct Answer: b) Queue.Queue is fully thread-safe with built-in locking primitives, whereas collections.deque operations are not globally thread-safe for multi-step mutations.
Explanation:
Queue.Queue provides built-in synchronization (mutexes and condition variables) designed specifically for producer-consumer threading patterns.

9. What happens when you call the .join() method on a running Thread object?

a) It terminates the thread immediately.
b) It blocks the calling thread until the thread whose join() method is called completes its execution.
c) It merges the memory space of the thread into the main process.
d) It releases the GIL back to the operating system.
Correct Answer: b) It blocks the calling thread until the thread whose join() method is called completes its execution.
Explanation:
join() is used for synchronization to ensure that the main program waits for background worker threads to finish before proceeding or exiting.

10. What is the function of the asyncio module in Python?

a) To provide multi-core parallel processing using separate system processes.
b) To write concurrent code using async/await syntax via cooperative multitasking on a single thread event loop.
c) To automatically remove the GIL from custom C extensions.
d) To manage thread scheduling priorities in the Linux kernel.
Correct Answer: b) To write concurrent code using async/await syntax via cooperative multitasking on a single thread event loop.
Explanation:
asyncio uses an event loop to manage asynchronous I/O operations cooperatively without spawning multiple OS threads.

11. What is a coroutine in Python's asyncio framework?

a) A standard OS-level thread managed by the scheduler.
b) A specialized function defined with async def that can be paused and resumed using the await keyword.
c) A background system process running on a separate CPU core.
d) An immutable data structure used for thread-safe communication.
Correct Answer: b) A specialized function defined with async def that can be paused and resumed using the await keyword.
Explanation:
Coroutines are cooperative subroutines that yield control back to the event loop when awaiting an I/O operation.

12. What does a Semaphore do in threading?

a) It restricts access to a critical section to exactly one thread at all times.
b) It maintains an internal counter that decrements on acquire() and increments on release(), permitting a specified maximum number of threads access.
c) It terminates threads that exceed a specific time limit.
d) It synchronizes start times across all worker threads.
Correct Answer: b) It maintains an internal counter that decrements on acquire() and increments on release(), permitting a specified maximum number of threads access.
Explanation:
Semaphores manage access pools, allowing up to N threads to access a resource concurrently (e.g., connection pools).

13. What is a race condition?

a) A performance benchmark measuring thread creation speed.
b) An undesirable situation where a system's output depends on the erratic sequence or timing of uncontrollable thread execution.
c) When two processes compete for CPU clock cycles.
d) An exception raised when a thread runs out of stack memory.
Correct Answer: b) An undesirable situation where a system's output depends on the erratic sequence or timing of uncontrollable thread execution.
Explanation:
Race conditions occur when multiple threads access shared mutable state without proper locking, leading to unpredictable data corruption.

14. How do you properly initialize and start a Thread in Python?

a) t = Thread(target=my_func); t.run()
b) t = Thread(target=my_func); t.start()
c) t = Thread(my_func).begin()
d) t = start_thread(my_func)
Correct Answer: b) t = Thread(target=my_func); t.start()
Explanation:
Calling start() creates a new native thread and invokes the target function inside it. Calling run() directly executes it synchronously on the current thread.

15. What is the purpose of the daemon property on a Thread object?

a) It gives the thread higher CPU scheduling priority.
b) It marks the thread as a background daemon; the Python program exits as soon as all non-daemon threads have exited, regardless of daemon threads still running.
c) It prevents the thread from ever encountering deadlocks.
d) It runs the thread in a separate OS process.
Correct Answer: b) It marks the thread as a background daemon; the Python program exits as soon as all non-daemon threads have exited, regardless of daemon threads still running.
Explanation:
Daemon threads are abruptly killed when the main program finishes, making them useful for background tasks like logging or heartbeats.

16. What is the function of threading.local()?

a) It creates variables that are shared globally across all threads.
b) It creates thread-local data storage where each thread has its own distinct, isolated instance of the attributes.
c) It restricts thread execution to the local CPU socket.
d) It caches function return values locally in RAM.
Correct Answer: b) It creates thread-local data storage where each thread has its own distinct, isolated instance of the attributes.
Explanation:
Thread-local storage ensures that data assigned to a thread-local object is invisible and inaccessible to other threads.

17. What is a ProcessPoolExecutor used for?

a) Managing asynchronous network sockets on a single thread.
b) Executing CPU-bound callables asynchronously across a pool of separate worker processes.
c) Managing background UI rendering tasks.
d) Pooling database connections across threads.
Correct Answer: b) Executing CPU-bound callables asynchronously across a pool of separate worker processes.
Explanation:
ProcessPoolExecutor uses multiprocessing under the hood, making it ideal for parallelizing CPU-intensive operations across multiple cores.

18. How are objects passed between processes in Python's multiprocessing module by default?

a) Via shared virtual memory pointers.
b) Via pickling (serialization) and deserialization over pipes or queues.
c) Via direct reference sharing in RAM.
d) Via TCP loopback sockets exclusively.
Correct Answer: b) Via pickling (serialization) and deserialization over pipes or queues.
Explanation:
Because processes have separate memory spaces, objects must be pickled to be sent between processes (unless using explicit SharedMemory).

19. What does the multiprocessing.Value object allow you to do?

a) Share a single primitive data type (like integer or float) safely across multiple processes using allocated shared memory.
b) Store thread-safe environment variables.
c) Measure the execution time of concurrent processes.
d) Encrypt data sent across network sockets.
Correct Answer: a) Share a single primitive data type (like integer or float) safely across multiple processes using allocated shared memory.
Explanation:
multiprocessing.Value and Array allocate memory from shared memory segments, allowing fast inter-process data sharing with optional locks.

20. What is livelock?

a) A state where threads are actively responding to each other's state changes without making any actual forward progress.
b) When a thread terminates unexpectedly due to an uncaught exception.
c) A deadlock that resolves itself automatically after a timeout.
d) High CPU utilization caused by busy-waiting loops.
Correct Answer: a) A state where threads are actively responding to each other's state changes without making any actual forward progress.
Explanation:
Unlike deadlocks where threads are blocked, in a livelock threads keep changing their states in response to each other without accomplishing tasks.

21. What is busy-waiting (or spinning)?

a) A technique where a thread repeatedly checks a condition in a tight loop rather than blocking or sleeping.
b) When the operating system pauses threads during high memory pressure.
c) The initialization phase of a ThreadPoolExecutor.
d) Waiting for network packets using asynchronous selectors.
Correct Answer: a) A technique where a thread repeatedly checks a condition in a tight loop rather than blocking or sleeping.
Explanation:
Busy-waiting wastes excessive CPU cycles and should be avoided in favor of Events, Condition variables, or Locks.

22. What is the purpose of threading.Barrier?

a) To block a set of threads until all of them have reached the barrier point, after which they are all released simultaneously.
b) To prevent unauthorized threads from accessing critical sections.
c) To stop thread execution when an exception occurs.
d) To limit the maximum number of active threads in a pool.
Correct Answer: a) To block a set of threads until all of them have reached the barrier point, after which they are all released simultaneously.
Explanation:
Barriers synchronize multiple threads at a milestone, ensuring no thread proceeds past the barrier until all participating threads arrive.

23. What is an event loop in asyncio?

a) A background operating system thread scheduler.
b) The core engine of asyncio that registers tasks, handles I/O multiplexing, and dispatches callbacks and coroutines.
c) A loop that restarts crashed threads automatically.
d) A multithreaded queue for passing messages between processes.
Correct Answer: b) The core engine of asyncio that registers tasks, handles I/O multiplexing, and dispatches callbacks and coroutines.
Explanation:
The event loop monitors all registered asynchronous events and runs coroutines cooperatively when their awaited events complete.

24. What is the difference between asyncio.gather() and asyncio.wait()?

a) gather() returns results in order and raises exceptions immediately or aggregates them, while wait() returns sets of completed and pending tasks giving finer-grained control.
b) gather() is synchronous, while wait() is asynchronous.
c) wait() only works with threads, while gather() works with processes.
d) There is no difference; they are aliases for the same function.
Correct Answer: a) gather() returns results in order and raises exceptions immediately or aggregates them, while wait() returns sets of completed and pending tasks giving finer-grained control.
Explanation:
asyncio.gather is convenient for running concurrent tasks and getting ordered results, whereas asyncio.wait offers robust control over timeouts and return conditions (e.g., FIRST_COMPLETED).

25. What does the GIL do when a Python thread performs an I/O operation like socket.recv()?

a) It holds the GIL tightly, blocking all other threads from running.
b) It releases the GIL, allowing other Python threads to execute Python code while the current thread waits for data.
c) It terminates the thread to save system resources.
d) It switches the thread to a separate process.
Correct Answer: b) It releases the GIL, allowing other Python threads to execute Python code while the current thread waits for data.
Explanation:
Releasing the GIL during blocking system/I/O calls is what makes multithreading beneficial for I/O-bound programs in Python.

26. Which Python keyword is used to pause a coroutine and wait for an awaitable object?

a) yield
b) await
c) async
d) pause
Correct Answer: b) await
Explanation:
The await keyword suspends execution of the surrounding coroutine until the awaited result is ready, yielding control back to the event loop.

27. Can you use standard threading Locks safely across different processes in Python?

a) Yes, threading Locks work identically across processes.
b) No, threading Locks only synchronize threads within the same process. Multiprocessing requires multiprocessing.Lock.
c) Only on Linux systems.
d) Yes, provided the lock is declared as global.
Correct Answer: b) No, threading Locks only synchronize threads within the same process. Multiprocessing requires multiprocessing.Lock.
Explanation:
Because processes have separate memory spaces, inter-process synchronization requires primitives from the multiprocessing module.

28. What is a reentrant lock (RLock)?

a) A lock that can be acquired multiple times by the same thread without causing a deadlock.
b) A lock that automatically releases itself after a set time limit.
c) A lock shared across multiple networked computers.
d) A lock used exclusively in asynchronous event loops.
Correct Answer: a) A lock that can be acquired multiple times by the same thread without causing a deadlock.
Explanation:
An RLock tracks which thread currently owns it; the owning thread can acquire it multiple times and must release it an equal number of times for it to unlock.

29. What is the primary risk of using daemon processes in multiprocessing?

a) They consume infinite CPU resources.
b) Daemon processes are forcefully terminated when their parent process exits, which may leave child processes, open files, or database connections in an inconsistent state.
c) They cannot communicate via pipes or queues.
d) They bypass operating system security permissions.
Correct Answer: b) Daemon processes are forcefully terminated when their parent process exits, which may leave child processes, open files, or database connections in an inconsistent state.
Explanation:
Daemon processes are not allowed to create child processes themselves, and their abrupt termination can corrupt resources if not handled carefully.

30. What does the concurrent.futures.Future object represent?

a) An asynchronous computation that has not necessarily finished yet.
b) A scheduled system timer for thread execution.
c) A persistent database connection pool.
d) A thread synchronization lock.
Correct Answer: a) An asynchronous computation that has not necessarily finished yet.
Explanation:
A Future encapsulates the eventual result of an asynchronous operation, providing methods to check status, cancel, or retrieve results.

31. How do you run a blocking synchronous function inside an asyncio event loop without blocking the main event loop thread?

a) Using loop.run_in_executor() with a ThreadPoolExecutor or ProcessPoolExecutor.
b) By prefixing the function with async def.
c) By calling time.sleep() inside the coroutine.
d) It is impossible; blocking functions cannot be run in asyncio.
Correct Answer: a) Using loop.run_in_executor() with a ThreadPoolExecutor or ProcessPoolExecutor.
Explanation:
run_in_executor offloads blocking synchronous calls to a separate thread or process pool so the event loop remains responsive.

32. What is the purpose of multiprocessing.Pool?

a) To manage a pool of worker processes and provide convenient methods like map(), apply_async(), and starmap() for parallel data processing.
b) To share thread-safe variables across threads.
c) To pool asynchronous network connections.
d) To balance network load across cluster nodes.
Correct Answer: a) To manage a pool of worker processes and provide convenient methods like map(), apply_async(), and starmap() for parallel data processing.
Explanation:
multiprocessing.Pool simplifies parallelizing tasks across multiple CPU cores by handling process creation and work distribution automatically.

33. What is starvation in concurrent programming?

a) When a process or thread is perpetually denied necessary resources (like CPU time or locks) to make progress.
b) When a program runs out of RAM during thread creation.
c) When network packets are dropped due to high latency.
d) When all worker threads finish their tasks and enter an idle state.
Correct Answer: a) When a process or thread is perpetually denied necessary resources (like CPU time or locks) to make progress.
Explanation:
Thread starvation usually happens with poor scheduling policies where higher-priority threads monopolize resources, starving lower-priority threads.

34. What is priority inversion?

a) A scenario where a high-priority thread is indirectly preempted by a low-priority thread because a medium-priority thread holds a resource the high-priority thread needs.
b) When threads execute in reverse order of their creation.
c) When the operating system swaps thread priorities randomly.
d) An error when acquiring locks out of sequence.
Correct Answer: a) A scenario where a high-priority thread is indirectly preempted by a low-priority thread because a medium-priority thread holds a resource the high-priority thread needs.
Explanation:
Priority inversion can cause severe system delays in real-time systems and is typically mitigated using priority inheritance.

35. What does asyncio.create_task() do?

a) Wraps a coroutine into a Task object and schedules its execution on the event loop immediately.
b) Spawns a new operating system thread in the background.
c) Creates a separate process for CPU-bound tasks.
d) Pauses the event loop until a task finishes.
Correct Answer: a) Wraps a coroutine into a Task object and schedules its execution on the event loop immediately.
Explanation:
Tasks are used to run coroutines concurrently in the background while the main code continues executing.

36. What is the difference between a Task and a Future in asyncio?

a) A Task is a subclass of Future that wraps and manages the execution of a coroutine; a Future is a lower-level container for a result not tied to a specific coroutine.
b) Tasks are used for multithreading, while Futures are used for multiprocessing.
c) Futures run synchronously, while Tasks run asynchronously.
d) There is no functional difference.
Correct Answer: a) A Task is a subclass of Future that wraps and manages the execution of a coroutine; a Future is a lower-level container for a result not tied to a specific coroutine.
Explanation:
Tasks drive coroutines to completion, whereas generic Futures represent any future result that might be set manually or via callbacks.

37. What is the purpose of the multiprocessing.Pipe() function?

a) It returns a pair of connection objects connected by a pipe, providing a two-way communication channel between two processes.
b) It pipes standard output from child processes to the terminal.
c) It creates a shared memory array across threads.
d) It streams data over TCP network sockets.
Correct Answer: a) It returns a pair of connection objects connected by a pipe, providing a two-way communication channel between two processes.
Explanation:
A Pipe is generally faster than a Queue for bidirectional communication between exactly two processes.

38. What is a producer-consumer problem?

a) A classic concurrency pattern where one or more producer threads/processes generate data items and place them into a buffer, while consumer threads/processes remove and process them.
b) An issue where database connections exceed the maximum pool limit.
c) A deadlock caused by circular lock acquisition.
d) When CPU cores overheat due to excessive threading.
Correct Answer: a) A classic concurrency pattern where one or more producer threads/processes generate data items and place them into a buffer, while consumer threads/processes remove and process them.
Explanation:
The producer-consumer pattern requires synchronized buffers (like Queue) to prevent race conditions when adding and removing items.

39. What does threading.Event().wait() do?

a) Blocks the calling thread until the internal flag of the Event object becomes true.
b) Waits for a specific number of seconds before starting a thread.
c) Terminates the event loop immediately.
d) Waits for all child processes to finish.
Correct Answer: a) Blocks the calling thread until the internal flag of the Event object becomes true.
Explanation:
An Event object manages an internal flag that can be set to true with set() and reset to false with clear(). wait() blocks until the flag is true.

40. Which Python module provides async network streams (TCP/UDP sockets)?

a) asyncio
b) multiprocessing
c) threading
d) socketserver
Correct Answer: a) asyncio
Explanation:
asyncio provides high-level APIs like asyncio.open_connection() and start_server() for asynchronous network programming.

41. What is lock coarsening?

a) An optimization technique where multiple adjacent synchronization lock operations on the same object are merged into a single larger lock scope.
b) Removing locks entirely to improve performance.
c) Splitting a large lock into multiple fine-grained locks.
d) Converting thread locks into process locks.
Correct Answer: a) An optimization technique where multiple adjacent synchronization lock operations on the same object are merged into a single larger lock scope.
Explanation:
Lock coarsening reduces synchronization overhead when multiple lock/unlock cycles happen close together on the same monitor/lock.

42. What is lock striping?

a) Dividing a data structure into multiple independent partitions, each protected by its own lock, to reduce contention and increase concurrency.
b) Removing locks from read-only operations.
c) Using a single global lock for all data structures.
d) Alternating between thread locks and process locks.
Correct Answer: a) Dividing a data structure into multiple independent partitions, each protected by its own lock, to reduce contention and increase concurrency.
Explanation:
Lock striping (such as in ConcurrentHashMap implementations) minimizes lock contention by allowing simultaneous access to different segments.

43. What is the purpose of multiprocessing.Manager()?

a) It provides a server process that controls python objects, allowing shared data types (like lists, dicts, and namespaces) to be shared safely across different processes.
b) It manages thread pool execution priorities.
c) It automatically restarts crashed worker threads.
d) It monitors CPU temperature during parallel tasks.
Correct Answer: a) It provides a server process that controls python objects, allowing shared data types (like lists, dicts, and namespaces) to be shared safely across different processes.
Explanation:
Managers allow proxy objects to be shared across processes, supporting complex data structures like shared dictionaries and lists.

44. What is cooperative multitasking?

a) A style of multitasking where processes or coroutines voluntarily yield control back to the scheduler or event loop periodically, rather than being forcibly preempted by the OS.
b) Multithreading where all threads share the same memory space.
c) Running processes across multiple networked computers.
d) Synchronizing threads using hardware barriers.
Correct Answer: a) A style of multitasking where processes or coroutines voluntarily yield control back to the scheduler or event loop periodically, rather than being forcibly preempted by the OS.
Explanation:
asyncio uses cooperative multitasking (via await), meaning control is yielded explicitly when awaiting I/O rather than interrupted arbitrarily.

45. What is preemption in operating systems?

a) The act of temporarily interrupting a running task (thread or process) by the OS scheduler without requiring its cooperation, to allocate CPU time to another task.
b) Voluntarily yielding control using the await keyword.
c) Waiting for a thread lock to be released.
d) Terminating a thread when an exception occurs.
Correct Answer: a) The act of temporarily interrupting a running task (thread or process) by the OS scheduler without requiring its cooperation, to allocate CPU time to another task.
Explanation:
OS threads use preemptive multitasking, where the kernel switches threads based on time slices, unlike asyncio's cooperative multitasking.

46. What happens if an exception is raised inside a thread spawned by threading.Thread?

a) It crashes the entire Python program immediately.
b) It prints a traceback to sys.stderr and terminates the thread silently, without affecting other running threads or crashing the main program (unless caught or handled via sys.excepthook).
c) It is automatically caught and returned by thread.join().
d) It restarts the thread automatically.
Correct Answer: b) It prints a traceback to sys.stderr and terminates the thread silently, without affecting other running threads or crashing the main program (unless caught or handled via sys.excepthook).
Explanation:
Unlike main execution threads, unhandled exceptions in background threads do not propagate to the main thread or crash the process by default.

47. How can you catch exceptions raised by tasks executed in a ThreadPoolExecutor?

a) By calling .result() on the Future object returned by executor.submit(), which re-raises any exception that occurred during execution.
b) By wrapping the executor in a try-except block when instantiating it.
c) Exceptions in thread pools cannot be caught.
d) By using sys.excepthook.
Correct Answer: a) By calling .result() on the Future object returned by executor.submit(), which re-raises any exception that occurred during execution.
Explanation:
Calling future.result() propagates exceptions raised inside the worker thread back to the calling thread.

48. What is the function of asyncio.Lock?

a) A primitive lock for asyncio coroutines ensuring mutually exclusive access to shared resources within a single-threaded event loop.
b) A multi-process locking mechanism.
c) A thread synchronization lock for CPython bytecodes.
d) A network socket lock.
Correct Answer: a) A primitive lock for asyncio coroutines ensuring mutually exclusive access to shared resources within a single-threaded event loop.
Explanation:
asyncio.Lock is non-blocking at the OS thread level but blocks coroutines cooperatively using await lock:.

49. What is an asynchronous generator in Python?

a) A generator function defined with async def that uses yield and can also await expressions.
b) A generator that runs on a separate CPU process.
c) A thread-safe list comprehension.
d) An event loop ticker.
Correct Answer: a) A generator function defined with async def that uses yield and can also await expressions.
Explanation:
Asynchronous generators allow yielding values asynchronously using async for loops.

50. What is the purpose of asyncio.as_completed()?

a) An iterator that yields futures as they complete, regardless of the order they were submitted.
b) Blocks until all futures are finished and returns them in submission order.
c) Cancels all pending tasks in the event loop.
d) Measures the total execution time of concurrent tasks.
Correct Answer: a) An iterator that yields futures as they complete, regardless of the order they were submitted.
Explanation:
as_completed allows processing results as soon as each individual asynchronous task finishes.

51. What is the main advantage of using uvloop over the default asyncio event loop?

a) It is implemented in Cython and built on top of libuv, offering significantly faster event loop performance and lower latency.
b) It allows asyncio to bypass the GIL entirely.
c) It converts asynchronous code into multi-process code automatically.
d) It provides built-in graphical user interface bindings.
Correct Answer: a) It is implemented in Cython and built on top of libuv, offering significantly faster event loop performance and lower latency.
Explanation:
uvloop is a drop-in replacement for the standard asyncio event loop that matches or exceeds Go networking performance.

52. What does a ThreadPoolExecutor do when shutdown(wait=True) is called?

a) It prevents any new tasks from being submitted and blocks the calling thread until all currently running and queued tasks have completed.
b) It terminates all running threads immediately.
c) It restarts the thread pool with fresh threads.
d) It flushes all futures from memory without waiting.
Correct Answer: a) It prevents any new tasks from being submitted and blocks the calling thread until all currently running and queued tasks have completed.
Explanation:
shutdown(wait=True) ensures graceful completion of pending work before releasing thread pool resources.

53. Can Python threads be forcefully killed from the outside?

a) Yes, using the thread.kill() method.
b) No, standard Python threads cannot be forcefully terminated safely from another thread; they must exit cooperatively (e.g., via flags or signals).
c) Yes, by calling sys.exit() from the main thread.
d) Yes, using multiprocessing.terminate().
Correct Answer: b) No, standard Python threads cannot be forcefully terminated safely from another thread; they must exit cooperatively (e.g., via flags or signals).
Explanation:
Forcibly killing a thread could leave locks acquired and shared memory corrupted, so Python intentionally lacks a thread-kill API.

54. What is the purpose of the contextvars module in Python concurrency?

a) To manage state that is local to a specific asynchronous context (like an asyncio task or thread), preventing data leakage in concurrent code.
b) To provide thread-safe database connection configurations.
c) To share global variables across processes.
d) To store environment variables securely.
Correct Answer: a) To manage state that is local to a specific asynchronous context (like an asyncio task or thread), preventing data leakage in concurrent code.
Explanation:
Context variables provide thread-local and task-local storage, essential for async frameworks where execution jumps between tasks on a single thread.

55. What is the difference between multiprocessing.Process.start() and multiprocessing.Process.run()?

a) start() spawns a new separate OS process to run the target function, whereas run() executes the target function directly in the current process.
b) run() is asynchronous, while start() is synchronous.
c) run() bypasses the GIL, while start() does not.
d) There is no difference.
Correct Answer: a) start() spawns a new separate OS process to run the target function, whereas run() executes the target function directly in the current process.
Explanation:
Similar to threading, calling run directly executes synchronously without spawning a new execution context.

56. What is the function of the 'spawn' start method in multiprocessing?

a) The parent process starts a fresh Python interpreter process, which only inherits necessary resources, making it safe across all operating systems (especially Windows and macOS).
b) It forks the entire process memory space instantly.
c) It creates lightweight threads instead of processes.
d) It shares memory pointers directly via kernel mapping.
Correct Answer: a) The parent process starts a fresh Python interpreter process, which only inherits necessary resources, making it safe across all operating systems (especially Windows and macOS).
Explanation:
'spawn' is the default start method on Windows and macOS due to safety limitations with fork in multi-threaded programs.

57. What is the function of the 'fork' start method in multiprocessing?

a) The parent process uses os.fork() to duplicate the entire Python interpreter process state, copying memory-on-write.
b) It spawns a fresh interpreter from scratch.
c) It creates an asynchronous event loop.
d) It manages thread pools.
Correct Answer: a) The parent process uses os.fork() to duplicate the entire Python interpreter process state, copying memory-on-write.
Explanation:
'fork' is the default on Unix platforms but can cause subtle deadlock issues if used in multi-threaded parent processes.

58. What is the function of the 'forkserver' start method in multiprocessing?

a) A server process is spawned when the program starts, and whenever a new process is needed, the forkserver forks it, avoiding fork safety issues.
b) It starts an asyncio network server.
c) It manages TCP socket connections across machines.
d) It pools database connections.
Correct Answer: a) A server process is spawned when the program starts, and whenever a new process is needed, the forkserver forks it, avoiding fork safety issues.
Explanation:
forkserver combines the fast startup of fork with the safety of spawn by avoiding multi-threaded fork issues.

59. What is an asynchronous iterator?

a) An object that implements __aiter__ and __anext__ methods, allowing asynchronous item retrieval via async for loops.
b) An iterator that runs across multiple CPU cores.
c) A thread-safe list.
d) An event loop timer.
Correct Answer: a) An object that implements __aiter__ and __anext__ methods, allowing asynchronous item retrieval via async for loops.
Explanation:
Async iterators enable pulling items asynchronously (e.g., fetching rows from an async database cursor).

60. What does asyncio.shield() do?

a) Protects an awaited expression from being cancelled if the surrounding task gets cancelled.
b) Prevents race conditions in thread locks.
c) Shields a process from being terminated by the OS.
d) Encrypts data sent through queues.
Correct Answer: a) Protects an awaited expression from being cancelled if the surrounding task gets cancelled.
Explanation:
If the outer coroutine is cancelled, the coroutine passed to shield continues running in the background.

61. What is the function of asyncio.run()?

a) Higher-level convenience function introduced in Python 3.7 that manages the event loop lifecycle, runs a coroutine, and closes the loop cleanly.
b) Spawns a background thread pool.
c) Runs synchronous functions asynchronously.
d) Starts a multiprocessing pool.
Correct Answer: a) Higher-level convenience function introduced in Python 3.7 that manages the event loop lifecycle, runs a coroutine, and closes the loop cleanly.
Explanation:
asyncio.run() is the standard entry point for running top-level async main functions in Python.

62. What is a green thread (or micro-thread)?

a) A thread managed entirely by a runtime library or virtual machine rather than the native operating system kernel.
b) An eco-friendly energy-saving CPU thread mode.
c) A Python thread that never acquires the GIL.
d) An asynchronous network socket.
Correct Answer: a) A thread managed entirely by a runtime library or virtual machine rather than the native operating system kernel.
Explanation:
Libraries like Gevent use green threads for cooperative concurrency, though Python's official async ecosystem relies on asyncio tasks and coroutines.

63. What is the primary risk of using global variables across multiple threads without locks?

a) Data corruption and race conditions due to uncoordinated reads and writes.
b) Automatic garbage collection of the variable.
c) Deadlock during initialization.
d) Forced process termination.
Correct Answer: a) Data corruption and race conditions due to uncoordinated reads and writes.
Explanation:
Shared mutable state accessed by multiple threads without synchronization primitives leads to unpredictable state bugs.

64. What does a multiprocessing.Event do?

a) Provides an inter-process synchronization flag equivalent to threading.Event, allowing processes to signal one another.
b) Triggers system interrupts across CPU cores.
c) Schedules process execution time.
d) Handles network socket events.
Correct Answer: a) Provides an inter-process synchronization flag equivalent to threading.Event, allowing processes to signal one another.
Explanation:
multiprocessing.Event uses shared memory flags to synchronize execution across independent processes.

65. What is the purpose of multiprocessing.BoundedSemaphore?

a) A semaphore that ensures its current value never exceeds its initial maximum value, raising an error if released too many times.
b) A semaphore limited to a specific CPU core.
c) A timeout lock for processes.
d) A thread synchronization limit.
Correct Answer: a) A semaphore that ensures its current value never exceeds its initial maximum value, raising an error if released too many times.
Explanation:
BoundedSemaphore guards against programming errors where release() is called more times than acquire().

66. What does the `asyncio.sleep()` function do?

a) Yields control back to the event loop for a specified number of seconds without blocking the thread.
b) Freezes the entire Python interpreter process.
c) Puts the current operating system thread to sleep.
d) Terminates the current asyncio task.
Correct Answer: a) Yields control back to the event loop for a specified number of seconds without blocking the thread.
Explanation:
Unlike time.sleep() which blocks the whole thread, asyncio.sleep() allows other coroutines to execute during the wait time.

67. How can you run multiple asyncio loops concurrently?

a) By running each event loop in a separate OS thread.
b) An OS thread can host multiple event loops simultaneously.
c) Event loops cannot be concurrent.
d) Using multiprocessing to share a single event loop.
Correct Answer: a) By running each event loop in a separate OS thread.
Explanation:
By default, one event loop runs per thread. Running multiple event loops requires assigning each to its own thread.

68. What is thread contention?

a) When multiple threads attempt to acquire the same lock or resource simultaneously, forcing some threads to wait and reducing concurrency efficiency.
b) When threads compete for network bandwidth.
c) An exception raised during thread creation.
d) When threads finish execution at the same time.
Correct Answer: a) When multiple threads attempt to acquire the same lock or resource simultaneously, forcing some threads to wait and reducing concurrency efficiency.
Explanation:
High lock contention creates bottlenecks where threads spend more time waiting for locks than doing useful work.

69. What is a daemon thread in Python?

a) A background thread that does not prevent the Python program from exiting when all non-daemon threads finish.
b) A thread that runs with root system permissions.
c) A thread immune to deadlocks.
d) A thread that manages memory garbage collection.
Correct Answer: a) A background thread that does not prevent the Python program from exiting when all non-daemon threads finish.
Explanation:
Daemon threads are automatically killed when the main program exits.

70. What is the purpose of the queue.Queue.task_done() method?

a) Indicates that a formerly enqueued task is complete, helping join() determine when all items have been processed.
b) Deletes the queue from memory.
c) Signals producers to stop generating items.
d) Resets the queue size counter.
Correct Answer: a) Indicates that a formerly enqueued task is complete, helping join() determine when all items have been processed.
Explanation:
Consumers call task_done() after processing an item so queue.join() knows when the workload is fully finished.

71. What is an asynchronous context manager?

a) An object that implements __aenter__ and __aexit__ methods, used with async with statements for asynchronous setup and teardown logic.
b) A context manager that runs across multiple processes.
c) A thread-safe lock manager.
d) An event loop initializer.
Correct Answer: a) An object that implements __aenter__ and __aexit__ methods, used with async with statements for asynchronous setup and teardown logic.
Explanation:
Async context managers allow performing asynchronous initialization (like connecting to a database pool) safely.

72. What is the primary benefit of using ProcessPoolExecutor over multiprocessing.Pool?

a) ProcessPoolExecutor implements the modern concurrent.futures interface, making it compatible with futures, timeouts, and callbacks across both threads and processes.
b) ProcessPoolExecutor uses zero memory.
c) multiprocessing.Pool is deprecated and removed in Python 3.
d) ProcessPoolExecutor bypasses serialization requirements.
Correct Answer: a) ProcessPoolExecutor implements the modern concurrent.futures interface, making it compatible with futures, timeouts, and callbacks across both threads and processes.
Explanation:
ProcessPoolExecutor provides a cleaner, more standardized future-based API compared to the older multiprocessing.Pool.

73. What happens if a thread holding a Lock raises an unhandled exception without releasing it?

a) The lock remains permanently locked, potentially causing deadlocks for other threads attempting to acquire it (unless using try/finally blocks).
b) Python automatically releases the lock.
c) The operating system restarts the thread.
d) The lock raises a RuntimeError.
Correct Answer: a) The lock remains permanently locked, potentially causing deadlocks for other threads attempting to acquire it (unless using try/finally blocks).
Explanation:
Locks must always be released in a `finally` block or used as context managers (`with lock:`) to guarantee release on exceptions.

74. How do context managers (`with` statement) help prevent lock deadlocks?

a) They guarantee that the lock's release() method is called automatically when exiting the block, even if an exception occurs.
b) They prevent threads from waiting more than 1 second.
c) They disable the GIL during critical sections.
d) They convert threads into asynchronous tasks.
Correct Answer: a) They guarantee that the lock's release() method is called automatically when exiting the block, even if an exception occurs.
Explanation:
Using `with lock:` ensures safe acquisition and release patterns without manual try/finally boilerplate.

75. What is the function of multiprocessing.cpu_count()?

a) Returns the number of CPUs/cores available in the system, useful for determining worker pool sizes in parallel processing.
b) Returns current CPU temperature.
c) Measures CPU clock speed.
d) Limits thread execution count.
Correct Answer: a) Returns the number of CPUs/cores available in the system, useful for determining worker pool sizes in parallel processing.
Explanation:
cpu_count() helps configure optimal ProcessPoolExecutor sizes matching physical or logical core counts.

76. What is the role of the select module in Python concurrency?

a) Provides low-level I/O multiplexing primitives (like select, poll, epoll) to monitor multiple file descriptors for readability or writability without blocking.
b) Selects optimal threads for execution.
c) Manages database query selection.
d) Selects active CPU cores.
Correct Answer: a) Provides low-level I/O multiplexing primitives (like select, poll, epoll) to monitor multiple file descriptors for readability or writability without blocking.
Explanation:
The select module forms the foundation upon which asyncio and high-performance network servers build asynchronous event loops.

77. What is an active wait loop?

a) A loop that continuously checks a condition without sleeping, consuming 100% CPU time.
b) An event loop waiting for async tasks.
c) A thread join synchronization call.
d) A process pool worker loop.
Correct Answer: a) A loop that continuously checks a condition without sleeping, consuming 100% CPU time.
Explanation:
Active waiting (busy-waiting) is inefficient and should be replaced with blocking synchronization primitives like Event or Condition.

78. Can asyncio tasks run across multiple threads simultaneously?

a) No, an asyncio event loop runs on a single thread by default, though different threads can run their own separate event loops.
b) Yes, asyncio automatically utilizes all CPU cores.
c) Yes, via multi-threaded coroutine execution.
d) Only when using multiprocessing.
Correct Answer: a) No, an asyncio event loop runs on a single thread by default, though different threads can run their own separate event loops.
Explanation:
asyncio is single-threaded cooperative concurrency; true parallelism requires multiprocessing or multi-threaded loop coordination.

79. What is the function of asyncio.run_coroutine_threadsafe()?

a) Allows submitting a coroutine from another OS thread to run safely inside an asyncio event loop running on a different thread.
b) Runs a thread safely inside an event loop.
c) Converts threads into coroutines.
d) Synchronizes multiple event loops.
Correct Answer: a) Allows submitting a coroutine from another OS thread to run safely inside an asyncio event loop running on a different thread.
Explanation:
This function acts as a bridge enabling synchronous or multi-threaded code to dispatch work into an asyncio event loop thread.

80. What is a SharedMemory object in Python's multiprocessing.shared_memory module?

a) A block of memory allocated by the OS kernel that can be accessed and modified directly by multiple independent processes without pickling overhead.
b) A shared RAM cache for threads.
c) A thread-safe dictionary.
d) A global process lock.
Correct Answer: a) A block of memory allocated by the OS kernel that can be accessed and modified directly by multiple independent processes without pickling overhead.
Explanation:
SharedMemory enables high-performance inter-process data sharing for large arrays and buffers.

81. What is the purpose of the queue.Queue.get_nowait() method?

a) Retrieves an item from the queue immediately if available, raising queue.Empty if the queue is currently empty, without blocking.
b) Clears all items from the queue instantly.
c) Waits indefinitely until an item appears.
d) Terminates the queue thread.
Correct Answer: a) Retrieves an item from the queue immediately if available, raising queue.Empty if the queue is currently empty, without blocking.
Explanation:
get_nowait() is the non-blocking equivalent of get(block=False).

82. What is the purpose of the queue.Queue.put_nowait() method?

a) Puts an item into the queue immediately if space is available, raising queue.Full if the queue is at capacity, without blocking.
b) Forces an item to the front of the queue.
c) Clears queue contents.
d) Bypasses queue locking.
Correct Answer: a) Puts an item into the queue immediately if space is available, raising queue.Full if the queue is at capacity, without blocking.
Explanation:
put_nowait() is the non-blocking equivalent of put(item, block=False).

83. What does a Barrier do when broken (e.g., via broken state or timeout)?

a) It raises a BrokenBarrierError across waiting threads, releasing them from blocking.
b) It restarts the entire thread pool.
c) It resets all locks automatically.
d) It terminates the Python process.
Correct Answer: a) It raises a BrokenBarrierError across waiting threads, releasing them from blocking.
Explanation:
If a thread times out or encounters an error while waiting at a Barrier, the barrier enters a broken state and raises BrokenBarrierError.

84. What is the function of threading.enumerate()?

a) Returns a list of all currently active Thread objects currently alive in the Python program.
b) Numbers threads sequentially.
c) Counts total CPU cores.
d) Lists active process IDs.
Correct Answer: a) Returns a list of all currently active Thread objects currently alive in the Python program.
Explanation:
threading.enumerate() includes daemon threads, main threads, and active worker threads.

85. What is the function of threading.current_thread()?

a) Returns the Thread object corresponding to the caller's thread of execution.
b) Returns the parent process ID.
c) Returns the current CPU core ID.
d) Returns the active lock count.
Correct Answer: a) Returns the Thread object corresponding to the caller's thread of execution.
Explanation:
current_thread() is often used for logging thread names and debugging concurrent executions.

86. What is the primary architectural difference between multithreading and multiprocessing in Python?

a) Threads share the same memory space within a single process and are subject to the GIL; processes run in separate memory spaces with independent interpreters, bypassing the GIL.
b) Threads are faster than processes for CPU-bound tasks.
c) Processes cannot communicate with each other.
d) Threads run on separate CPU sockets automatically.
Correct Answer: a) Threads share the same memory space within a single process and are subject to the GIL; processes run in separate memory spaces with independent interpreters, bypassing the GIL.
Explanation:
This fundamental distinction dictates whether to use threading (for I/O bound tasks) or multiprocessing (for CPU bound tasks) in Python.
← Previous: Python Modules & Packages MCQs
Next →: Python OOP MCQs
JavaScript Strings MCQs

JavaScript Strings MCQs

Strings in JavaScript represent sequences of UTF-16 code units used to store and manipulate textual data. Declared using single quotes,…

By MCQs Generator
Java Multithreading & Concurrency MCQs

Java Multithreading & Concurrency MCQs

Java multithreading and concurrency are core pillars for building high-performance, responsive applications that execute multiple tasks simultaneously. Utilizing the java.util.concurrent…

By MCQs Generator
Python Advanced MCQs

Python Advanced MCQs

Advanced Python programming moves beyond basic syntax and data structures into the fundamental mechanics of how CPython executes code under…

By MCQs Generator