Sha256: ea92bc95350dd85102eeb2e7d9e4c2751b91f847da3ab0b26981763203589571

Contents?: true

Size: 890 Bytes

Versions: 38

Compression:

Stored size: 890 Bytes

Contents

#!/usr/bin/env ruby

require_relative '../lib/async'

def sleep_sort(items)
	Async::Reactor.run do |task|
		# Where to save the sorted items:
		sorted_items = []
		
		items.each do |item|
			# Spawn an async task...
			task.async do |nested_task|
				# Which goes to sleep for the specified duration:
				nested_task.sleep(item)
				
				# And then appends the item to the sorted array:
				sorted_items << item
			end
		end
		
		# Wait for all children to complete.
		task.children.each(&:wait)
		
		# Return the result:
		sorted_items
	end.wait # Wait for the entire process to complete.
end

# Calling at the top level blocks the thread:
puts sleep_sort(5.times.collect{rand}).inspect

# Calling in your own reactor allows you to control the asynchronus behaviour:
Async::Reactor.run do |task|
	3.times do
		task.async do
			puts sleep_sort(5.times.collect{rand}).inspect
		end
	end
end

Version data entries

38 entries across 38 versions & 1 rubygems

Version Path
async-1.14.0 examples/sleep_sort.rb
async-1.13.1 examples/sleep_sort.rb
async-1.13.0 examples/sleep_sort.rb
async-1.12.0 examples/sleep_sort.rb
async-1.11.0 examples/sleep_sort.rb
async-1.10.3 examples/sleep_sort.rb
async-1.10.2 examples/sleep_sort.rb
async-1.10.1 examples/sleep_sort.rb
async-1.10.0 examples/sleep_sort.rb
async-1.9.1 examples/sleep_sort.rb
async-1.9.0 examples/sleep_sort.rb
async-1.8.0 examples/sleep_sort.rb
async-1.7.0 examples/sleep_sort.rb
async-1.6.0 examples/sleep_sort.rb
async-1.5.0 examples/sleep_sort.rb
async-1.4.1 examples/sleep_sort.rb
async-1.4.0 examples/sleep_sort.rb
async-1.3.0 examples/sleep_sort.rb