Skip to content

Commit

Permalink
Documentation.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Nov 22, 2024
1 parent 79cfb7d commit 395a7d1
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/async/work_pool.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@
require "etc"

module Async
# A simple work pool that offloads work to a background thread.
class WorkPool
# A handle to the work being done.
class Handle
# Create a new handle.
#
# @parameter scheduler [Async::Scheduler] The scheduler that is managing the fiber.
# @parameter fiber [Async::Fiber] The fiber that is waiting for the work to complete.
# @parameter work [Proc] The work to be done.
def initialize(scheduler, fiber, work)
@scheduler = scheduler
@fiber = fiber
Expand All @@ -20,6 +27,7 @@ def initialize(scheduler, fiber, work)
@error = nil
end

# Call the work and notify the scheduler when it is done.
def call
@thread = ::Thread.current

Expand All @@ -35,6 +43,7 @@ def call
end
end

# Wait for the work to complete.
def wait
@scheduler.block(self, nil)

Expand All @@ -45,13 +54,17 @@ def wait
end
end

# Cancel the work.
def cancel!
@work = nil
@fiber = nil # Don't call unblock.
@thread&.raise(Interrupt)
end
end

# Create a new work pool.
#
# @parameter size [Integer] The number of threads to use.
def initialize(size: Etc.nprocessors)
@queue = ::Thread::Queue.new

Expand All @@ -60,6 +73,7 @@ def initialize(size: Etc.nprocessors)
end
end

# Close the work pool. Kills all outstanding work.
def close
@queue.close

Expand All @@ -68,6 +82,9 @@ def close
end
end

# Offload work to a thread.
#
# @parameter work [Proc] The work to be done.
def call(work)
handle = Handle.new(::Fiber.scheduler, ::Fiber.current, work)

Expand Down

0 comments on commit 395a7d1

Please sign in to comment.