class Async::Container::Threaded::Child

Represents a running child thread from the point of view of the parent container.

def self.fork(**options)

@parameter options [Hash] Additional options to to the new child instance.

Start a new child thread and execute the provided block in it.
def self.fork(**options)
	self.new(**options) do |thread|
		::Thread.new do
			# This could be a configuration option (see forked implementation too):
			::Thread.handle_interrupt(SignalException => :immediate) do
				yield Instance.for(thread)
			end
		end
	end
end

def as_json(...)

@returns [Hash] The request as a hash.

Convert the child process to a hash, suitable for serialization.
def as_json(...)
	{
		name: @thread.name,
		status: @status&.as_json,
	}
end

def close

Invoke {#terminate!} and then {#wait} for the child thread to exit.
def close
	self.terminate!
	self.wait
ensure
	super
end

def finished(error = nil)

Invoked by the @waiter thread to indicate the outcome of the child thread.
def finished(error = nil)
	if error
		Console.error(self) {error}
	end
	
	@status ||= Status.new(error)
	self.close_write
end

def initialize(name: nil)

@parameter name [String] The name to use for the child thread.

Initialize the thread.
def initialize(name: nil)
	super()
	
	@status = nil
	
	@thread = yield(self)
	@thread.report_on_exception = false
	@thread.name = name
	
	@waiter = ::Thread.new do
		begin
			@thread.join
		rescue Exit => exit
			finished(exit.error)
		rescue Interrupt
			# Graceful shutdown.
			finished
		rescue Exception => error
			finished(error)
		else
			finished
		end
	end
end

def interrupt!

Raise {Interrupt} in the child thread.
def interrupt!
	@thread.raise(Interrupt)
end

def kill!

Invoke {Thread#kill} on the child thread.
def kill!
	# Killing a thread does not raise an exception in the thread, so we need to handle the status here:
	@status = Status.new(:killed)
	
	@thread.kill
end

def name

@returns [String]
Get the name of the thread.
def name
	@thread.name
end

def name= value

@parameter value [String] The name to set.
Set the name of the thread.
def name= value
	@thread.name = value
end

def restart!

Raise {Restart} in the child thread.
def restart!
	@thread.raise(Restart)
end

def terminate!

Raise {Terminate} in the child thread.
def terminate!
	@thread.raise(Terminate)
end

def to_json(...)

@returns [String] The request as JSON.

Convert the request to JSON.
def to_json(...)
	as_json.to_json(...)
end

def to_s

@returns [String]
A human readable representation of the thread.
def to_s
	"\#<#{self.class} #{@thread.name}>"
end

def wait

@returns [Status]
Wait for the thread to exit and return he exit status.
def wait
	if @waiter
		@waiter.join
		@waiter = nil
	end
	
	return @status
end