multithreadingerlangkernelcoroutinegreen-threads

What exactly makes Erlang process, green thread, coroutine "lighter" than kernel thread? What about context switching that's heavy?


Possible Duplicate:
Technically why is processes in Erlang more efficient than OS threads?

Any time Erlang processes or green threads or coroutines are mentioned, they are always described as "light weight" when compared to kernel threads. The reason usually given is that kernel threads involve context switching which is slow.

But what exactly about context switching that is slow? And how much slower is it compared to switching green threads in userland?

Is context switching the main (only?) factor that accounts for the difference in performance and memory consumption between an event-driven program such as Nignx and a multi-processing program such as Apache?


Solution

  • Context switching on preemptive, monolithic, multitasking operating systems involves one of two paths, either an implicit yield to the scheduler via some system service call (sleep, mutex acquire, waiting for an event, blocking I/O) or via an interrupt and the scheduler deciding to swap running tasks.

    When a task is swapped by the scheduler, a few heavyweight things happen:

    A green thread task is pretty straightforward, as I understand it. A user-mode dispatcher directs a coroutine to run until the coroutine yields. A few differences in above:

    In short, a context switch in user mode involves a few library calls and writing to the stack pointer register. A context switch in kernel mode involves interrupts, user/kernel transition, and system level behavior like address space state changes and cache flushes.