views:

273

answers:

3

What are the differences between a "coroutine" and a "thread"?

A: 

It depends on the language you're using. For example in Lua they are the same thing (the variable type of a coroutine is called thread).

Usually though coroutines implement voluntary yielding where (you) the programmer decide where to yield, ie, give control to another routine.

Threads instead are automatically managed (stopped and started) by the OS, and they can even run at the same time on multicore CPUs.

Andreas Bonini
+2  A: 

Coroutines are a form of sequential processing: only one is executing at any given time (just like subroutines AKA procedures AKA functions -- they just pass the baton among each other more fluidly;-).

Threads are (at least conceptually) a form of concurrent processing: multiple threads may be executing at any given time. (Traditionally, on single-CPU, single-core machines, that concurrency was simulated with some help from the OS -- nowadays, since so many machines are multi-CPU and/or multi-core, threads will de facto be executing simulaneously, not just "conceptually";-).

Alex Martelli
+2  A: 

In a word: preemption. Coroutines act like jugglers that keep handing off to each other a well-rehearsed points. Threads (true threads) can be interrupted at almost any point and then resumed later. Of course, this brings with it all sorts of resource conflict issues, hence Python's infamous GIL - Global Interpreter Lock.

Many thread implementations are actually more like coroutines.

Peter Rowell