Eli Sadoff
Eli Sadoff

Reputation: 7308

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.

Upvotes: 1

Views: 123

Answers (1)

Aetherus
Aetherus

Reputation: 8898

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

Upvotes: 4

Related Questions