-
-
Notifications
You must be signed in to change notification settings - Fork 91
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Work pool for (more) efficient handling of
blocking_operation_wait
.
- Loading branch information
Showing
2 changed files
with
104 additions
and
10 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# frozen_string_literal: true | ||
|
||
# Released under the MIT License. | ||
# Copyright, 2024, by Samuel Williams. | ||
|
||
require "etc" | ||
|
||
module Async | ||
class WorkPool | ||
class Handle | ||
def initialize(scheduler, fiber, work) | ||
@scheduler = scheduler | ||
@fiber = fiber | ||
@work = work | ||
@thread = nil | ||
|
||
@finished = false | ||
|
||
@result = nil | ||
@error = nil | ||
end | ||
|
||
def call | ||
@thread = ::Thread.current | ||
|
||
if @work | ||
@result = @work.call | ||
end | ||
rescue => @error | ||
ensure | ||
@thread = nil | ||
@finished = true | ||
@scheduler.unblock(self, @fiber) | ||
end | ||
|
||
def wait | ||
@scheduler.block(self, nil) | ||
|
||
if @error | ||
raise @error | ||
else | ||
return @result | ||
end | ||
end | ||
|
||
def cancel! | ||
@work = nil | ||
@thread&.raise(Interrupt) | ||
end | ||
end | ||
|
||
def initialize(size: Etc.nprocessors) | ||
@queue = ::Thread::Queue.new | ||
|
||
@threads = size.times.map do | ||
::Thread.new(&method(:run)) | ||
end | ||
end | ||
|
||
def close | ||
@queue.close | ||
|
||
while thread = @threads.pop | ||
thread.kill | ||
end | ||
end | ||
|
||
def call(work) | ||
handle = Handle.new(::Fiber.scheduler, ::Fiber.current, work) | ||
|
||
begin | ||
@queue << handle | ||
|
||
result = handle.wait | ||
handle = nil | ||
|
||
return result | ||
ensure | ||
handle&.cancel! | ||
end | ||
end | ||
|
||
private def run | ||
while job = @queue.pop | ||
job.call | ||
end | ||
rescue Interrupt | ||
# Exiting. | ||
end | ||
end | ||
end |