Eli Sadoff Eli Sadoff - 5 months ago 7
Ruby Question

Can I initialize a thread that is asleep in ruby?

I'm messing around with threads in ruby and I was trying to see what would happen if I did something like this

x = 0
a = Thread.new{ x += 1 while true }
b = Thread.new{ x -= 1 while true }


but I want
a
and
b
to start at the same time. Can I initialize
a
and
b
both as sleeping threads and awake them at the same time? Thanks.

Answer

In ruby, you can't create an asleep thread, but a thread can put itself into sleep until some other thread wakes it up.

x = 0
a = Thread.new{ Thread.stop; x += 1 while true }
b = Thread.new{ Thread.stop; x -= 1 while true }

a.run
b.run