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.24.1 examples/sleep_sort.rb
async-1.24.0 examples/sleep_sort.rb
async-1.23.0 examples/sleep_sort.rb
async-1.22.2 examples/sleep_sort.rb
async-1.22.1 examples/sleep_sort.rb
async-1.22.0 examples/sleep_sort.rb
async-1.21.0 examples/sleep_sort.rb
async-1.20.1 examples/sleep_sort.rb
async-1.20.0 examples/sleep_sort.rb
async-1.19.0 examples/sleep_sort.rb
async-1.18.0 examples/sleep_sort.rb
async-1.17.1 examples/sleep_sort.rb
async-1.17.0 examples/sleep_sort.rb
async-1.16.0 examples/sleep_sort.rb
async-1.15.5 examples/sleep_sort.rb
async-1.15.4 examples/sleep_sort.rb
async-1.15.3 examples/sleep_sort.rb
async-1.15.2 examples/sleep_sort.rb
async-1.15.1 examples/sleep_sort.rb
async-1.15.0 examples/sleep_sort.rb