Sha256: ce60a17ae94148d32a77adbed90ea935905ca0b760ac1aa0ed13c2902f6bed0f

Contents?: true

Size: 1.07 KB

Versions: 7

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2019-2024, by Samuel Williams.
# Copyright, 2020, by Brian Morearty.
# Copyright, 2024, by Patrik Wenger.

require_relative "../async/reactor"

# Extensions to all Ruby objects.
module Kernel
	# Run the given block of code synchronously, but within a reactor if not already in one.
	#
	# @yields {|task| ...} The block that will execute asynchronously.
	# 	@parameter task [Async::Task] The task that is executing the given block.
	#
	# @public Since *Async v1*.
	# @asynchronous Will block until given block completes executing.
	def Sync(annotation: nil, &block)
		if task = ::Async::Task.current?
			if annotation
				task.annotate(annotation) {yield task}
			else
				yield task
			end
		elsif scheduler = Fiber.scheduler
			::Async::Task.run(scheduler, &block).wait
		else
			# This calls Fiber.set_scheduler(self):
			reactor = Async::Reactor.new
			
			begin
				return reactor.run(annotation: annotation, finished: ::Async::Condition.new, &block).wait
			ensure
				Fiber.set_scheduler(nil)
			end
		end
	end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
async-2.23.0 lib/kernel/sync.rb
async-2.22.0 lib/kernel/sync.rb
async-2.21.3 lib/kernel/sync.rb
async-2.21.2 lib/kernel/sync.rb
async-2.21.1 lib/kernel/sync.rb
async-2.21.0 lib/kernel/sync.rb
async-2.20.0 lib/kernel/sync.rb