Sha256: 5fafd3550d76cf8d8542ab7cf96f92b87671bf18aae0ab26b56514ab14339769

Contents?: true

Size: 1.06 KB

Versions: 3

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2021-2024, 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
		
		alias value= resolve
		
		# 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 wait
			@condition&.wait
			return @value
		end
		
		alias value wait
	end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
async-2.17.0 lib/async/variable.rb
async-2.16.1 lib/async/variable.rb
async-2.16.0 lib/async/variable.rb