â€ē Async â€ē Source â€ē Async â€ē Condition

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.info "Waiting for condition..."
		value = condition.wait
		Console.info "Condition was signalled: #{value}"
	end
	
	Async do |task|
		sleep(1)
		Console.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 Async v1.

Definitions

def initialize

Create a new condition.

Implementation

def initialize
	@ready = ::Thread::Queue.new
end

def wait

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

Signature

returns Object

Implementation

def wait
	@ready.pop
end

def empty?

Signature

returns Boolean

If there are no fibers waiting on this condition.

Implementation

def empty?
	@ready.num_waiting.zero?
end

def waiting?

Signature

returns Boolean

Is any fiber waiting on this notification?

Implementation

def waiting?
	!self.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 empty?
	
	ready = self.exchange
	
	ready.num_waiting.times do
		ready.push(value)
	end
	
	ready.close
	
	return nil
end

Discussion