Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coroutine vs Fiber difference clarification

In the book Linux System Programming, 2nd Edition, the difference between coroutines and fiber is explained as follows:

Coroutines and fibers provide a unit of execution even lighter in weight than the thread (with the former being their name when they are a programming language construct, and the latter when they are a system construct).

I have some example of Coroutines (language constructs) but unable to find the example of Fibers.

Can anyone provide me some example of Fiber (a system construct)?

like image 855
kasyauqi Avatar asked Mar 23 '17 17:03

kasyauqi


People also ask

Are fibers coroutines?

Fibers (sometimes called stackful coroutines or user mode cooperatively scheduled threads) and stackless coroutines (compiler synthesized state machines) represent two distinct programming facilities with vast performance and functionality differences.

Is coroutine a green thread?

Coroutines: Exactly fibers, except not OS-managed. Goroutines: They claim to be unlike anything else, but they seem to be exactly green threads, as in, process-managed in a single address space and multiplexed onto system threads.

What are the benefits of using coroutines?

Lightweight: You can run many coroutines on a single thread due to support for suspension, which doesn't block the thread where the coroutine is running. Suspending saves memory over blocking while supporting many concurrent operations. Fewer memory leaks: Use structured concurrency to run operations within a scope.

What is a coroutine in programming?

A coroutine is an instance of suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread.


1 Answers

You could take a look at boost.coroutine2 and boost.fiber (C++ libraries) - both use the same context switching mechanism (callcc()/continuation) from boost.context.

In short - the difference between coroutines and fibers is, that the context switch between fibers is managed by a scheduler (selects the next fiber ...). Coroutines don't have a concept of a scheduler.

A more detailed explanation of the difference between coroutines and fibers can be read in N4024: Distinguishing coroutines and fibers.

like image 69
xlrg Avatar answered Sep 28 '22 06:09

xlrg