Reputation: 3928
I am trying to create an infinite loop in the main ruby thread, while having infinite loops in spawned threads, but this doesn't work:
my_threads = []
for i in 1..2 do
puts "Creating thread #{i}"
my_threads << Thread.new(i) do |j|
loop do
sleep(1)
puts "work in #{Thread.current.object_id}"
end
end
end
my_threads.each do |t|
t.join
end
loop do
sleep(1)
puts 'work in main thread'
end
I need it this way because in my Rails app, I cannot use ActiveRecord objects inside of a thread, as explained here:
so I need a main thread that runs a loop, while having spawned threads run their own loops all concurrently.
The code above however does this:
work in 79515570work in 79515510
work in 79515510work in 79515570
work in 79515510work in 79515570
work in 79515570work in 79515510
work in 79515570work in 79515510
work in 79515570
work in 79515510
work in 79515570
work in 79515510
work in 79515570work in 79515510
It never reaches the main thread loop. How can I accomplish this?
Upvotes: 2
Views: 1744
Reputation: 37409
The code in your main thread is stopped here:
my_threads.each do |t|
t.join
end
What join
does is make the current thread wait until the the thread object it is called on finishes its run.
To resolve this, simply skip the above block:
my_threads = []
for i in 1..2 do
puts "Creating thread #{i}"
my_threads << Thread.new(i) do |j|
loop do
sleep(1)
puts "work in #{Thread.current.object_id}"
end
end
end
loop do
sleep(1)
puts 'work in main thread'
end
# work in 84665270
# work in 84665760
# work in main thread
# work in 84665270
# work in 84665760
# work in main thread
# work in 84665270
# work in 84665760
# work in main thread
# work in 84665270
# work in 84665760
Upvotes: 3