Sha256: 86b23bf1a7dc71ca981ad73ede8788bc44f44d7bb9b60cacd8ce6ffbcf3e609b

Contents?: true

Size: 1.07 KB

Versions: 4

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2021-2022, by Samuel Williams.

require_relative 'condition'

module Async
	# A synchronization primitive that allows one task to wait for another task to resolve a value.
	class Variable
		# Create a new variable.
		#
		# @parameter condition [Condition] The condition to use for synchronization.
		def initialize(condition = Condition.new)
			@condition = condition
			@value = nil
		end
		
		# Resolve the value.
		#
		# Signals all waiting tasks.
		#
		# @parameter value [Object] The value to resolve.
		def resolve(value = true)
			@value = value
			condition = @condition
			@condition = nil
			
			self.freeze
			
			condition.signal(value)
		end
		
		# Whether the value has been resolved.
		#
		# @returns [Boolean] Whether the value has been resolved.
		def resolved?
			@condition.nil?
		end
		
		# Wait for the value to be resolved.
		#
		# @returns [Object] The resolved value.
		def value
			@condition&.wait
			return @value
		end
		
		# Alias for {#value}.
		def wait
			self.value
		end
	end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
async-2.14.2 lib/async/variable.rb
async-2.14.1 lib/async/variable.rb
async-2.14.0 lib/async/variable.rb
async-2.13.0 lib/async/variable.rb