I’m reading about threads in the pickaxe book.
To understand what’s going on I was trying to run the following code:
threads=[]
3.times do |i|
threads[i]=Thread.new do
puts i
end
end
It ran ok, but nothing appeared on the console. I was expecting each of
the three threads to print ‘their’ position in the thread array.
The point of this exercise was to look at threads while they are working
concurrently, before calling the thread.join method.
I guess I’m misunderstanding the concept because this doesn’t work.
my questions are:
what’s wrong with the above code
can I write a program that will create M threads each of which
loops from 1 to N and all of them print concurrently to the console
something like “Thread #{m} is now on number #{n}”
can I write a program that will create M threads each of which
loops from 1 to N and all of them print concurrently to the console
something like “Thread #{m} is now on number #{n}”
I’m not an expert using threads, but it seems that the program
terminates
before the threads have a chance to do anything. Try putting a sleep 1
after
the cycle and you’ll see what you expect.
It ran ok, but nothing appeared on the console. I was expecting each of
the three threads to print ‘their’ position in the thread array.
The point of this exercise was to look at threads while they are working
concurrently, before calling the thread.join method.
I guess I’m misunderstanding the concept because this doesn’t work.
As Stefano already answered, the main thread is finishing before the
child threads do anything. That’s why the method join exists, so that
the main thread can wait for the other threads.
threads = (1…3).map do |i|
Thread.new(i) do |j|
puts j
end
end
threads.each {|t| t.join }
my questions are:
what’s wrong with the above code
can I write a program that will create M threads each of which
loops from 1 to N and all of them print concurrently to the console
something like “Thread #{m} is now on number #{n}”
M = 3
N = 10
threads = (1…M).map do |i|
Thread.new(i) do |thread_id|
N.times do |n|
puts “Thread #{thread_id}, #{n}”
sleep(rand(2))
end
end
end
threads.each {|t| t.join }
The sleep makes each thread wait a random time each iteration, so you
see how they interleave.
Jesus.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.