Foundationপ্রথম নীতি থেকে
LEVEL 5 · Programming Languages

Coroutine

কোরুটিন

Function যা মাঝপথে yield করে control ফেরত দেয়, পরে resume হলে ঠিক সেই জায়গা আর সেই local state নিয়ে চলে — cooperative multitasking-এর unit।

also: coroutines, generator

Subroutine return = stack frame ফেলে দেওয়া; coroutine suspend = frame জমা রেখে যাওয়া:

def counter():
    i = 0
    while True:
        yield i          # এখানে ঘুমাও, i মনে রাখো
        i += 1

c = counter()
next(c); next(c); next(c)   # 0, 1, 2 — state টিকে আছে
  • Symmetric (সরাসরি পরস্পরকে hand-off) বনাম asymmetric (yield → caller) — generator asymmetric
  • Stackful coroutine (Go goroutine, boost.context) যেকোনো depth থেকে suspend; stackless (Python async, C++20) শুধু marked জায়গায়
  • Implementation: পুরো stack swap বনাম state-machine transform (async/await compile করে CPS-এ)
  • OS thread-এর সাথে পার্থক্য: kernel জানে না, switch user-space-এ — হাজার হাজার coroutine এক thread-এ