Last active
November 14, 2021 10:49
-
-
Save akhal3d96/e18e03227e842d2b3349bbe4ff1afb33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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