在主线程中创建无限循环,同时在生成的线程中有无限循环

时间:2014-07-23 16:31:39

标签: ruby multithreading

我试图在主ruby线程中创建一个无限循环,同时在生成的线程中有无限循环,但这不起作用:

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

我需要这样,因为在我的Rails应用程序中,我不能在线程中使用ActiveRecord对象,如下所述:

https://stackoverflow.com/questions/24903230/activerecord-object-freezes-thread-in-multi-threaded-script

所以我需要一个运行循环的主线程,同时生成的线程同时运行它们自己的循环。

上面的代码可以这样做:

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

它永远不会到达主线程循环。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

主线程中的代码在此处停止:

my_threads.each do |t|
    t.join
end

join做的是让当前线程等到调用它的线程对象完成运行。

要解决此问题,只需跳过上述块:

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