Else branch in select

Hi all,

Please consider this:

gizmo = Channel(Bool).new

spawn do
  gizmo.send true
end

select
when signal = gizmo.receive
  puts "trapped #{signal}"
else
  puts "fubar"
end

I can’t receive from the channel with the else branch. Without the else it works as expected.

What do i miss? Probably something very essential.

Regards, Karl

P. S.: I read Ibarasti as well as some Go examples and the select manual but couldn’t get any further.

The gist of it is the else branch makes the select non-blocking. I.e. if there isn’t a value in the channel ready to be received, it’ll go to the else branch versus waiting for a value. In this specific case the fiber you spawn never gets a chance to run before the select, so there is no value waiting to be received so it goes to the else branch and program exits.

You need to do something to let the fiber be able to run before the select so that there is a value ready to be received. E.g. Fiber.yield in between the spawn and select.

1 Like

He, thank you! Fiber.yield in between made it. It was already there - just some lines below :crazy_face::sunglasses:.

I knew that it must have been something simple like that - let’s say i got that notorious mental block.

Best regards, Karl