Async SourceAsyncCondition

class Condition

A synchronization primitive, which allows fibers to wait until a particular condition is (edge) triggered. Zero or more fibers can wait on a condition. When the condition is signalled, the fibers will be resumed in order.

Example

require 'async'

Sync do
	condition = Async::Condition.new
	
	Async do
		Console.logger.info "Waiting for condition..."
		value = condition.wait
		Console.logger.info "Condition was signalled: #{value}"
	end
	
	Async do |task|
		task.sleep(1)
		Console.logger.info "Signalling condition..."
		condition.signal("Hello World")
	end
end

Output

0.0s     info: Waiting for condition...
1.0s     info: Signalling condition...
1.0s     info: Condition was signalled: Hello World

Signature

public

Since stable-v1.

Nested

Definitions

def wait

Queue up the current fiber and wait on yielding the task.

Signature

returns Object

Implementation

def wait
	@waiting.stack(FiberNode.new(Fiber.current)) do
		Fiber.scheduler.transfer
	end
end

def empty?

Is any fiber waiting on this notification?

Signature

returns Boolean

Implementation

def empty?
	@waiting.empty?
end

def signal(value = nil)

Signal to a given task that it should resume operations.

Signature

parameter value Object | Nil

The value to return to the waiting fibers.

Implementation

def signal(value = nil)
	return if @waiting.empty?
	
	waiting = self.exchange
	
	waiting.each do |fiber|
		Fiber.scheduler.resume(fiber, value) if fiber.alive?
	end
	
	return nil
end

Discussion