The piece of code: https://play.crystal-lang.org/#/r/3j42 should be dead since line7 and line12 both send to channel.
The clone of this code in go: https://play.golang.org/p/99RTrc57vOP is deadlock sometimes(if every time select the first case) via: https://golang.org/ref/spec#Select_statements (If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection.)
You have written
idle = Channel(Int32).new(1)
source = Channel(Int32).new()
spawn do
loop do
job = source.receive
select
when idle.send(job)
puts "haha"
when worker = idle.receive
spawn do
puts worker
idle.send(1)
end
end
end
end
i = 0
while i < 2
source.send(i)
i += 1
end
sleep 5.second
which is different to your Go code.
If you convert the crystal code to be equivalent to your Go code, you get this: https://play.crystal-lang.org/#/r/3j6k
@RX14 https://play.crystal-lang.org/#/r/3j6k should be deadlock sometimes if runtime scheduler selected first when pattern twice in a row.
And update my first go code: https://play.golang.org/p/QJu0syva68x along with https://play.crystal-lang.org/#/r/3j42
The select statement works pseudo-randomly. I am sending two values on source. When the select statement chooses idle.send(job) twice in a row at the start of the program, the second time
blocks sending to idle.
But who said it works pseudo randomly?
Sorry I don鈥檛 know select behavior in crystal different with golang. Thanks for answer.
Select behaviour hasn't really been thought about in that much detail to make it non-deterministic. It might change to be random in the future. But currently it's just the first one.
Got it, thanks again.
Think again about it now and I notice even if select first one every time, it should be deadlock. First time of loop: receive data from source chan and sent to idle, meanwhile the loop in main fiber can send data to source chan, and then second time of select select first pattern again, because idle not be consumed, deadlock here I think.
I didn't look at the example, but select was never really tested well so it might have many bugs. I would recommend not using it for the moment.
OK~
@asterite or use it, find bugs, fix bugs?
@asterite select works fine.
@ariesdevil does this make it easier to understand? https://play.crystal-lang.org/#/r/3jnw
@RX14 I don't think it does: https://github.com/crystal-lang/crystal/issues/3900
@bew Nobody is working on parallelism or select, so yes, you could report bugs but nobody is going to fix them anytime soon, so it's better to just avoid the parts of the language that are buggy.