ApocalypticSnail
ApocalypticSnail

Reputation: 3

Creating multiple identical threads in Ruby

What I woul dlike to do is to create multiple threads calling the same method with slightly different arguments each time, like this:

x = 1
argument = 3
while x <= 10 do #10 is the number of desired threads
    Thread.new{
        puts do.stuff(argument)
    }.join
    x += 1
    arguments += 1
end

My problem is that this code causes the main thread to stop until the declared thread is finished. Is there any way I can create these threads so that they will run concurrently?
Thanks.

Upvotes: 0

Views: 101

Answers (1)

falsetru
falsetru

Reputation: 368954

The code is joining (waiting the thread to be terminated; causing the 2nd thread run after 1st thread finish, 3rd thread run after 2nd thread, ...) inside the loop.

Create threads, and wait them outside the loop.

arguments = "3"
threads = 10.times.map {
  Thread.new {
    puts do.stuff(arguments)
  }
  # NOTE: no join here.
}
threads.each { |t| t.join }

Upvotes: 1

Related Questions