3 ms·
What’s a good example implementation of stackful coroutines?
by girvo 9y ago
What’s a good example implementation of stackful coroutines?
- RussianCow 9y agoAny sort of "green thread" implementation, such as Python's greenlets.
- ufo 9y agoLua coroutines work like this.
- anonacct37 9y agoWould golang count?
- ioquatix 9y agoYes go would fit into the green thread bucket pretty well.
- ioquatix 9y agoThere are two kinds of stackful coroutines - fibers and green threads. The difference is that fibers stay on the thread they were created on, while green threads can transit between OS threads. There have also been projects to cooperatively schedule OS level threads to minimise latency, but that's a bit different. I don't know that many decent green thread implementations [off the top of my head], but an interesting one is yahns: https://yhbt.net/yahns/design_notes.txt https://yhbt.net/yahns/design_notes.txt - to me, green threads have all the benefits of coroutines but all of the downsides of multi-threaded programming. I implemented fiber based concurrency for C++ here: https://github.com/kurocha/async https://github.com/kurocha/async. An example would be https://github.com/kurocha/async-network/blob/d1d2bf12eb2d9b259ecc59f2e4a5cf0756c441e4/test/Async/Network/Test.Socket.cpp#L55 https://github.com/kurocha/async-network/blob/d1d2bf12eb2d9b... - calling read yields the fiber if it would block as implemented here: https://github.com/kurocha/async/blob/2edef4d6990259cc60cc307b6de2ab35b97560f1/source/Async/Protocol/Stream.cpp#L33-L54 https://github.com/kurocha/async/blob/2edef4d6990259cc60cc30... I implemented almost exactly the same model for Ruby here: https://github.com/socketry/async https://github.com/socketry/async and if you are interested in how it works, see these projects which build on it: https://github.com/socketry/async#see-also https://github.com/socketry/async#see-also
- Tarean 9y agoHaskell does async IO by default using green threads. GHC allocates Thread State Objects which completely represent a (green) thread on the heap. A capabillity which represents a cpu core contains a queue of TSO's. If a thread blocks on something it can also move to a different queue which is used for thread synchronization, blocking on computations from other threads, io etc.