Sha256: 45525b3aafa95d92fe67a38b7c44f3cd4cec209fd6a8db113b28b4471968a504

Contents?: true

Size: 1.08 KB

Versions: 2

Compression:

Stored size: 1.08 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2023, by Samuel Williams.

module Async
	module Actor
		class Variable
			def self.fulfill(variable)
				variable.set(yield)
				variable = nil
			rescue => error
				variable&.fail(error)
				variable = nil
			ensure
				# throw, etc:
				variable&.fail(RuntimeError.new("Invalid flow control!"))
			end
			
			def initialize
				@set = nil
				@value = nil
				
				@guard = Thread::Mutex.new
				@condition = Thread::ConditionVariable.new
			end
			
			def set(value)
				@guard.synchronize do
					raise "Variable already set!" unless @set.nil?
					
					@set = true
					@value = value
					@condition.broadcast
				end
			end
			
			def fail(error)
				@guard.synchronize do
					raise "Variable already set!" unless @set.nil?
					
					@set = false
					@error = error
					@condition.broadcast
				end
			end
			
			def get
				@guard.synchronize do
					while @set.nil?
						@condition.wait(@guard)
					end
					
					if @set
						return @value
					else
						raise @error
					end
				end
			end
		end
	end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
async-actor-0.1.1 lib/async/actor/variable.rb
async-actor-0.1.0 lib/async/actor/variable.rb