Sha256: ef942291910905891d8a98ad1021d8e812b0555b75fb064ab72c218ea6cd50c8

Contents?: true

Size: 1.16 KB

Versions: 3

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

class Threaded
	def initialize(&block)
		@channel = Channel.new
		@thread = Thread.new(&block)
		
		@waiter = Thread.new do
			begin
				@thread.join
			rescue Exception => error
				finished(error)
			else
				finished
			end
		end
	end
	
	attr :channel
	
	def close
		self.terminate!
		self.wait
	ensure
		@channel.close
	end
	
	def interrupt!
		@thread.raise(Interrupt)
	end
	
	def terminate!
		@thread.raise(Terminate)
	end
	
	def wait
		if @waiter
			@waiter.join
			@waiter = nil
		end
		
		@status
	end
	
	protected
	
	def finished(error = nil)
		@status = Status.new(error)
		@channel.out.close
	end
end

class Forked
	def initialize(&block)
		@channel = Channel.new
		@status = nil
		
		@pid = Process.fork do
			Signal.trap(:INT) {raise Interrupt}
			Signal.trap(:INT) {raise Terminate}
			
			@channel.in.close
			
			yield
		end
		
		@channel.out.close
	end
	
	attr :channel
	
	def close
		self.terminate!
		self.wait
	ensure
		@channel.close
	end
	
	def interrupt!
		Process.kill(:INT, @pid)
	end
	
	def terminate!
		Process.kill(:TERM, @pid)
	end
	
	def wait
		unless @status
			_pid, @status = ::Process.wait(@pid)
		end
		
		@status
	end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
async-container-0.16.5 examples/minimal.rb
async-container-0.16.4 examples/minimal.rb
async-container-0.16.3 examples/minimal.rb