Module: Kernel

Defined in:
lib/kernel/sync.rb,
lib/kernel/async.rb

Overview

Extensions to all Ruby objects.

Instance Method Summary collapse

Instance Method Details

#AsyncObject

Run the given block of code in a task, asynchronously, creating a reactor if necessary.

The preferred method to invoke asynchronous behavior at the top level.

  • When invoked within an existing reactor task, it will run the given block

asynchronously. Will return the task once it has been scheduled.

  • When invoked at the top level, will create and run a reactor, and invoke

the block as an asynchronous task. Will block until the reactor finishes running.



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/kernel/async.rb', line 41

def Async(...)
	if current = ::Async::Task.current?
		return current.async(...)
	else
		reactor = ::Async::Reactor.new
		
		begin
			return reactor.run(...)
		ensure
			Fiber.set_scheduler(nil)
		end
	end
end

#Sync(&block) ⇒ Object

Run the given block of code synchronously, but within a reactor if not already in one.



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/kernel/sync.rb', line 34

def Sync(&block)
	if task = ::Async::Task.current?
		yield task
	else
		reactor = Async::Reactor.new
		
		begin
			return reactor.run(finished: ::Async::Condition.new, &block).wait
		ensure
			Fiber.set_scheduler(nil)
		end
	end
end