|
| 1 | +# Getting Started |
| 2 | + |
| 3 | +This guide explains how to use `async-await` for implementing some common concurrency patterns. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +Add the gem to your project: |
| 8 | + |
| 9 | +~~~ bash |
| 10 | +$ bundle add async-await |
| 11 | +~~~ |
| 12 | + |
| 13 | +## Usage |
| 14 | + |
| 15 | +### "async" Keyword |
| 16 | + |
| 17 | +This gem provides {ruby Async::Await} which introduces the `async` keyword. This keyword is used to define asynchronous methods. The method will return an `Async::Task` object, which can be waited on to get the result. |
| 18 | + |
| 19 | +``` ruby |
| 20 | +require 'async/await' |
| 21 | + |
| 22 | +class Coop |
| 23 | + include Async::Await |
| 24 | + |
| 25 | + async def count_chickens(area_name) |
| 26 | + 3.times do |i| |
| 27 | + sleep rand |
| 28 | + |
| 29 | + puts "Found a chicken in the #{area_name}!" |
| 30 | + end |
| 31 | + end |
| 32 | + |
| 33 | + async def count_all_chickens |
| 34 | + # These methods all run at the same time. |
| 35 | + count_chickens("garden") |
| 36 | + count_chickens("house") |
| 37 | + |
| 38 | + # We wait for the result |
| 39 | + count_chickens("tree").wait |
| 40 | + end |
| 41 | +end |
| 42 | + |
| 43 | +coop = Coop.new |
| 44 | +coop.count_all_chickens |
| 45 | +``` |
| 46 | + |
| 47 | +This interface was originally designed as a joke, but may be useful in some limited contexts. It is not recommended for general use. |
| 48 | + |
| 49 | +### Enumerable |
| 50 | + |
| 51 | +This gem provides {ruby Async::Await::Enumerable} which adds async support to the `Enumerable` module. This allows you to use concurrency in a more functional style. |
| 52 | + |
| 53 | +``` ruby |
| 54 | +require "async/await/enumerable" |
| 55 | + |
| 56 | +[1, 2, 3].async_each do |i| |
| 57 | + sleep rand |
| 58 | + puts i |
| 59 | +end |
| 60 | +``` |
| 61 | + |
| 62 | +This will run the block for each element in the array concurrently. |
| 63 | + |
| 64 | +#### Using a Semaphore |
| 65 | + |
| 66 | +In order to prevent unlimited concurrency, you can use a semaphore to limit the number of concurrent tasks. This is useful when you want to limit the number of concurrent tasks to a specific number. |
| 67 | + |
| 68 | +``` ruby |
| 69 | +require "async/await/enumerable" |
| 70 | +require "async/semaphore" |
| 71 | + |
| 72 | +semaphore = Async::Semaphore.new(2) |
| 73 | + |
| 74 | +[1, 2, 3].async_each(parent: semaphore) do |i| |
| 75 | + sleep rand |
| 76 | + puts i |
| 77 | +end |
| 78 | +``` |
0 commit comments