File: async_method.rb

package info (click to toggle)
ruby-async 1.30.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 536 kB
  • sloc: ruby: 3,651; makefile: 4
file content (60 lines) | stat: -rwxr-xr-x 1,027 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative '../lib/async'

module Async::Methods
	def sleep(*args)
		Async::Task.current.sleep(*args)
	end

	def async(name)
		original_method = self.method(name)
		
		define_method(name) do |*args|
			Async::Reactor.run do |task|
				original_method.call(*args)
			end
		end
	end

	def await(&block)
		block.call.wait
	end
	
	def barrier!
		Async::Task.current.children.each(&:wait)
	end
end

include Async::Methods

async def count_chickens(area_name)
	3.times do |i|
		sleep rand
		
		puts "Found a chicken in the #{area_name}!"
	end
end

async def find_chicken(areas)
	puts "Searching for chicken..."
	
	sleep rand * 5
	
	return areas.sample
end

async def count_all_chckens
	# These methods all run at the same time.
	count_chickens("garden")
	count_chickens("house")
	count_chickens("tree")
	
	# Wait for all previous async work to complete...
	barrier!
	
	puts "There was a chicken in the #{find_chicken(["garden", "house", "tree"]).wait}"
end

count_all_chckens