WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Expert · question 62 of 100

What are the differences between cooperative and preemptive multitasking in Python? Discuss their implications on application design.?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

In Python, multitasking refers to the ability of a program to perform multiple tasks concurrently. The two main approaches to multitasking are cooperative and preemptive multitasking.

Cooperative multitasking is a technique where each task yields control to other tasks voluntarily. This means that each task is responsible for deciding when to give up control and allow other tasks to run. Cooperative multitasking is often used in environments where tasks are not time-critical, such as user interfaces, where it is more important to avoid locking up the interface than to optimize the execution speed of individual tasks.

Preemptive multitasking, on the other hand, is a technique where the operating system decides when to switch between tasks. Each task is given a slice of time to execute, and the operating system interrupts the task when its slice is over and switches to the next task. Preemptive multitasking is used in environments where tasks are time-critical, such as real-time systems, where it is important to guarantee that tasks execute within a certain time frame.

In Python, cooperative multitasking can be implemented using coroutines, also known as generators. Coroutines are functions that can be paused and resumed at specific points, allowing other coroutines to run in between. This allows tasks to yield control to other tasks when they are waiting for external events, such as I/O operations.

Here is an example of using coroutines for cooperative multitasking:

    import asyncio
    
    async def task1():
        print('Task 1 started')
        await asyncio.sleep(1)
        print('Task 1 finished')
    
    async def task2():
        print('Task 2 started')
        await asyncio.sleep(2)
        print('Task 2 finished')
    
    async def main():
        await asyncio.gather(task1(), task2())
    
    asyncio.run(main())

In this example, the asyncio module is used to run the main coroutine, which schedules the execution of the task1 and task2 coroutines using the asyncio.gather function. The coroutines are implemented using the async def syntax and use the await keyword to pause their execution when waiting for the sleep function to complete.

Preemptive multitasking in Python can be implemented using threads or processes. Threads are lightweight units of execution that run within a single process, while processes are separate instances of the Python interpreter that can run in parallel. The threading and multiprocessing modules provide APIs for creating and managing threads and processes.

Here is an example of using threads for preemptive multitasking:

    import threading
    
    def task1():
        print('Task 1 started')
        time.sleep(1)
        print('Task 1 finished')
    
    def task2():
        print('Task 2 started')
        time.sleep(2)
        print('Task 2 finished')
    
    t1 = threading.Thread(target=task1)
    t2 = threading.Thread(target=task2)
    
    t1.start()
    t2.start()
    
    t1.join()
    t2.join()

In this example, two threads are created using the Thread class from the threading module. The threads are started using the start method, which causes them to execute their respective tasks concurrently. The join method is used to wait for the threads to complete before exiting the program.

It is important to note that while cooperative multitasking is simpler to implement than preemptive multitasking, it is also less efficient and can lead to performance issues when dealing with large numbers of tasks or tasks that take a long time to complete. Therefore, preemptive multitasking is usually the preferred approach for performance-critical applications.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics