thread_pool

Ahmed Khaled · @nemoload · over 2 years

Creates a thread pool that takes a block and run it in parallel with different jobs and returns a list of the results

def thread_pool(pool_size: 4, jobs:, &block)
threads = []
results = []
mutex = Mutex.new
pool_size.times do
threads << Thread.new do
while !jobs.empty? do
job = jobs.pop(true)
result = block.call(job)
mutex.synchronize { results << result }
end
end
end
threads.map(&:join)
results
end
0 · 0 · 0