Ruby理解多线程

Ruby理解多线程,ruby,multithreading,Ruby,Multithreading,我正在尝试按照以下exmaple:在ruby中执行多线程循环: 我复制了代码并写下了以下内容: module Enumerable def ignore_exception begin yield rescue Exception => e STDERR.puts e.message end end def in_parallel(n) t_queue

我正在尝试按照以下exmaple:在ruby中执行多线程循环:

我复制了代码并写下了以下内容:

module Enumerable

    def ignore_exception
        begin
            yield
        rescue Exception => e
            STDERR.puts e.message
        end
    end
    def in_parallel(n)
        t_queue = Queue.new
        threads = (1..n).map {
            Thread.new{ 
                while x = t_queue.deq
                    ignore_exception{ yield(x[0]) }
                end
            }
        }
        each{|x| t_queue << [x]}
        n.times{ t_queue << nil }
        threads.each{|t| 
            t.join 
            unless t[:out].nil?
                puts t[:out]
            end
        }
    end
end

ids.in_parallel(10){ |id|
 conn = open_conn(loc)
 out = conn.getData(id)
 Thread.current[:out] = out
}

我的理解是,它将一次排出10个项目的队列,按照id处理循环中的块,并在最后连接10个线程,然后重复,直到完成。在运行这段代码之后,我有时会得到不同的结果,特别是当我的ID小于10时,我不明白为什么会发生这种情况。虽然我可以在服务器端检查这些ID的输出是否存在,但有一半的时间它不会为多达一半的ID输出任何内容。例如,如果正确的输出是get id 1和get id 2,它将只打印出{get id 1}或{get id 2}或{get id 1,get id 2}。我的问题是,我对这段代码的理解是否正确?

我代码中的问题是open\u conn函数调用,它不是线程安全的。我通过同步获取连接句柄修复了该问题:

connLock = Mutex.new
ids.in_parallel(10){ |id|
 conn = nil
 connLock.synchronize {
    conn = open_conn(loc)
 }
 out = conn.getData(id)
 Thread.current[:out] = out
}
还应通过以下方式用于循环并行化:

 ids.peach(10){ |id| ... }