Skip to content

Instantly share code, notes, and snippets.

@akhal3d96
Last active November 14, 2021 10:49
Show Gist options
  • Save akhal3d96/e18e03227e842d2b3349bbe4ff1afb33 to your computer and use it in GitHub Desktop.
Save akhal3d96/e18e03227e842d2b3349bbe4ff1afb33 to your computer and use it in GitHub Desktop.
# pool_size: number of threads
# jobs: A queue (See: https://rubyapi.org/3.0/o/queue)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment