mysqlrubymultithreadingmutexsynchronize

How to get local variable value in Mutex.synchronize?


I'm working on make code multi-threaded for faster data analysis. To avoid multi-threaded database connections' problem, I use Mutex to lock it.

lock = Mutex.new()
thread_num.times do |i|
    threads << Thread.new do
        lock.synchronize{
             records = db_proxy.query(account_id) 
             result = process_records(records) 
        }        
    end
end

process_records is also time-consuming, but as a regular method, it supports multi-thread calls. It needs output from mdb_proxy.query, how can I take process_records out of lock.synchronize, while make it wait for the result from mdb_proxy.query, I tried following but got local variable exception

lock = Mutex.new()
    thread_num.times do |i|
        threads << Thread.new do
            lock.synchronize{
                 records = mdb_proxy.query(account_id) 
            }   
            result = process_records(records) 
        end
    end

Solution

  • Assign records to what block returns:

    records = lock.synchronize { mdb_proxy.query(account_id) }