spawnto make something work in the background without blocking the main execution.
spawncreates a lightweight thread called
Fibers are very cheap to create and you can easily create tens of thousands of
Fibers on a single core.
spawnto make stuff work in the background but how do we get something back from a
Channels come to play.
Channelis a channel between a sender and the receiver. Therefore a
Channellets each other communicate with
Channel(String).new. Note that we are creating a
receivemessages with type of
spawn. You might ask ‘Why are we sending message in the background?’ Well,
sendis 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
spawnto 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.