Last active
March 16, 2022 05:28
-
-
Save gfx/2126a5aafba0f2161373bcda316a1fd0 to your computer and use it in GitHub Desktop.
MiniThreadPool - A minimum viable thread pool implementation for Ruby
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
class MiniThreadPool | |
def initialize(size: 8, abort_on_exception: true) | |
@queue = Queue.new | |
@join_all = false | |
@threads = [] | |
size.times do | |
thr = Thread.new do | |
loop do | |
break if @join_all && @queue.empty? | |
begin | |
job = @queue.pop(true) # non-blocking dequeue | |
rescue ThreadError => e | |
# retry if queue is empty | |
sleep 0.1 | |
next | |
end | |
job.call | |
end | |
# end of the thread | |
end | |
thr.abort_on_exception = abort_on_exception | |
@threads << thr | |
end | |
end | |
def enqueue(&job) | |
@queue.push(job) | |
end | |
def join_all | |
@join_all = true | |
@threads.each do |thr| | |
thr.join | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment