MCS-201 · Unit 15

Python Advanced Concepts

Section 4 of 5

Block 4 · Unit 15Python Advanced Concepts10 min · Section 4 of 5

15.4Coroutines and Cooperative Multitasking

Covers IGNOU MCS-201 §15.5

A normal function runs from start to finish once called. A coroutine can stop in the middle, let something else run, and later continue where it left off. Programs that wait a lot, such as web servers waiting for network replies, use coroutines to handle many tasks at once in a single thread.

Subroutines and coroutines

Subroutine (ordinary function)Coroutine
EntryOne entry point; always starts at the topCan be resumed at each point where it suspended
SuspensionCannot pause; runs to the end, then returnsCan pause (yield or await) and resume later
ControlThe caller waits until it returnsGives control back voluntarily, then continues
CoordinationA main function calls subroutines in orderCoroutines pass control among themselves, often through a scheduler (event loop)
State between callsLocal variables are lost on returnLocal variables are kept while suspended

Cooperative multitasking, threads and coroutines

In cooperative multitasking, each task voluntarily gives up control when it reaches a waiting point, so another task can run. Nothing interrupts a task against its will.

ThreadsCoroutines
Who switchesThe operating system’s scheduler, at any moment (preemptive)The program itself, only at yield/await points (cooperative)
Number of OS threadsOne per threadUsually all in one thread
CostHeavier: each has its own stack, managed by the OSVery light: thousands are cheap
Data-sharing risksSwitches can happen mid-operation; locks are often neededSwitches happen only at known points; fewer race conditions
Best forCPU work in other languages; blocking librariesMany tasks that mostly wait (network, files, timers)

Coroutines give concurrency (many tasks in progress, taking turns), not parallelism (tasks running at the same instant on different cores).

Generator-based coroutines: send()

Before async/await existed, Python coroutines were built from generators. Besides producing values with yield, a generator can receive values: value = yield pauses, and gen.send(x) resumes it with value set to x. A coroutine must first be started (primed) with next(gen) so that it reaches its first yield.

Key takeaways

  • Coroutines generalise subroutines: they can suspend and resume.
  • Cooperative multitasking: tasks hand over control voluntarily.
  • Threads are switched by the OS; coroutines switch only at yield/await.
  • Generator coroutines receive data with send() after priming with next().

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What can a coroutine do that an ordinary function cannot?

Show answer

Answer: C. Suspend in the middle and later resume from the same point

Ordinary functions run to completion once called; coroutines can pause and continue.

Question 2 · multiple choice

Who decides when to switch between coroutines?

Show answer

Answer: B. The coroutines themselves, at yield or await points

This is cooperative multitasking, as opposed to the preemptive switching of OS threads.

Question 3 · multiple choice

What does this program print?

Python · quiz_send.py
def doubler():
    result = None
    while True:
        x = yield result
        result = x * 2

d = doubler()
next(d)
print(d.send(5), d.send(7))
Show answer

Answer: C. 10 14

Each send resumes the coroutine with x set to the sent value; it then loops back and yields the doubled result.

Question 4 · multiple choice

Why must a generator-based coroutine be primed with next()?

Show answer

Answer: D. To run it to its first yield, where it can receive a sent value

A just-created generator has not started; sending a non-None value to it raises TypeError.

Question 5 · multiple choice

Which statement about coroutines and threads is true?

Show answer

Answer: B. Coroutines switch only at known points, so they need fewer locks than threads

Cooperative switching happens only at yield/await, which limits unexpected interleaving; coroutines do not speed up CPU-bound work.

Question 6 · short answer

Compare subroutines and coroutines in three points.

Show worked answer

(1) Entry: a subroutine has one entry point and always starts from the beginning, while a coroutine can be resumed at each point where it previously suspended. (2) Suspension: a subroutine cannot pause; it runs to completion and returns, losing its local variables, while a coroutine can suspend (with yield or await), keep its local state and continue later. (3) Control: subroutines are called and coordinated by a main function, and the caller waits for each to finish; coroutines pass control to one another (or to an event loop) voluntarily, which allows cooperative multitasking.

↑ ↓ move↵ openTab switch type