spawn
to make something work in the background without blocking the main execution.spawn
creates a lightweight thread called Fiber
. Fiber
s are very cheap to create and you can easily create tens of thousands of Fiber
s on a single core.spawn
to make stuff work in the background but how do we get something back from a Fiber
.Channel
s come to play.Channel
is a channel between a sender and the receiver. Therefore a Channel
lets each other communicate with send
and receive
methods.Channel
with Channel(String).new
. Note that we are creating a Channel
which will send
and receive
messages with type of String
.spawn
. You might ask ‘Why are we sending message in the background?’ Well, send
is a blocking operation and if we do that in the main program we gonna block the program forever.channel.send "Hello?"
. Now that we know why we use spawn
to send a message let’s continue.spawn
. Then we receive it back with channel.receive
. In this example the message is Hello?
so this program prints Hello?
and then finishes.