Skip to content

Instantly share code, notes, and snippets.

@gfx
Last active March 16, 2022 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfx/2126a5aafba0f2161373bcda316a1fd0 to your computer and use it in GitHub Desktop.
Save gfx/2126a5aafba0f2161373bcda316a1fd0 to your computer and use it in GitHub Desktop.
MiniThreadPool - A minimum viable thread pool implementation for Ruby
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