slouc / concurrency-in-scala-with-ce

Introduction to concepts of asynchronous and concurrent programming in Scala, based on the Cats Effect library.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How a fiber's non blocking behaviour is implemented?

riccardocorbella opened this issue · comments

The section in which is given the definition of a Fiber says that

Also, blocking a fiber doesn't block the underlying thread.

Since in text there isn't an explanation for this behaviour I think that would be great to add it. I'd submit a PR but unfortunately I haven't yet understood how it's possible to implement such a behaviour 😅.

👋 I'll try to drop an explanation in here today if no one else gets to it first, but the very short answer is "callbacks". When a sequential thread wishes to suspend itself (delay the execution of the next action), the only mechanism for this is blocking, since the next action is… the next thing the thread will do if allowed. However, when an asynchronous process wishes to suspend itself, all that needs to happen is to just delay running the callback which executes the next steps. So when a fiber is "blocked", what it really means is the continuation of that fiber has not yet been scheduled.

@djspiewak Thanks for dropping by!

@riccardocorbella I just realized I forgot to mention it back then - following your comment, I added a commit that hopefully explains this reasoning a bit better and adds a couple of other missing insights, such as the abstraction layers. Let me know if it makes it more clear now, or is there something else we should add.