├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── why_what_template.md └── workflows │ └── ci.yaml ├── .gitignore ├── .rspec ├── .rubocop.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── async_scheduler.gemspec ├── bin ├── console └── setup ├── codecov.yaml ├── lib ├── async_scheduler.rb └── async_scheduler │ ├── cross_thread_usage_detector.rb │ ├── scheduler.rb │ └── version.rb ├── sig └── async_std_scheduler.rbs └── spec ├── async_scheduler_spec.rb ├── basics └── threading_spec.rb ├── blockings ├── address_resolve_spec.rb ├── read_spec.rb ├── sleep_spec.rb ├── timeout_spec.rb └── write_spec.rb └── spec_helper.rb /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Describe the bug 11 | 12 | A clear and concise description of what the bug is. 13 | If applicable, add screenshots to help explain your problem. 14 | 15 | 16 | ## To Reproduce 17 | Steps to reproduce the behavior: 18 | 1. Go to '...' 19 | 2. Click on '....' 20 | 3. Scroll down to '....' 21 | 4. See error 22 | 23 | ## Expected behavior 24 | A clear and concise description of what you expected to happen. 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: feature request 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/why_what_template.md: -------------------------------------------------------------------------------- 1 | ## Why 2 | 3 | 4 | 5 | ## What 6 | 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push] 3 | jobs: 4 | test: 5 | strategy: 6 | fail-fast: false 7 | matrix: 8 | os: [ubuntu-latest, macos-latest] 9 | ruby: ['3.1'] 10 | runs-on: ${{ matrix.os }} 11 | steps: 12 | - uses: ruby/setup-ruby@v1 13 | with: 14 | ruby-version: ${{ matrix.ruby }} 15 | bundler-cache: true # runs 'bundle install' and caches installed gems automatically 16 | - run: sudo gem install bundler -v 2.3.7 17 | - run: brew install shared-mime-info 18 | if: matrix.os == 'macos-latest' 19 | - uses: actions/checkout@v2 20 | - run: bundle install 21 | - run: bundle exec rspec 22 | env: 23 | CI: true 24 | - uses: codecov/codecov-action@v1 25 | with: 26 | file: ./coverage/coverage.xml 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | 10 | # rspec failure tracking 11 | .rspec_status 12 | Gemfile.lock 13 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | --require spec_helper 4 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | TargetRubyVersion: 3.0 3 | 4 | Style/StringLiterals: 5 | Enabled: true 6 | EnforcedStyle: double_quotes 7 | 8 | Style/StringLiteralsInInterpolation: 9 | Enabled: true 10 | EnforcedStyle: double_quotes 11 | 12 | Layout/LineLength: 13 | Max: 120 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [Unreleased] 2 | 3 | ## [0.1.1] - 2023-10-14 4 | 5 | - Initial release 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or 22 | advances of any kind 23 | * Trolling, insulting or derogatory comments, and personal or political attacks 24 | * Public or private harassment 25 | * Publishing others' private information, such as a physical or email 26 | address, without their explicit permission 27 | * Other conduct which could reasonably be considered inappropriate in a 28 | professional setting 29 | 30 | ## Enforcement Responsibilities 31 | 32 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 33 | 34 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 35 | 36 | ## Scope 37 | 38 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 39 | 40 | ## Enforcement 41 | 42 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at heyjudejudejude1968@gmail.com. All complaints will be reviewed and investigated promptly and fairly. 43 | 44 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 45 | 46 | ## Enforcement Guidelines 47 | 48 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 49 | 50 | ### 1. Correction 51 | 52 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 53 | 54 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 55 | 56 | ### 2. Warning 57 | 58 | **Community Impact**: A violation through a single incident or series of actions. 59 | 60 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 61 | 62 | ### 3. Temporary Ban 63 | 64 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 65 | 66 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 67 | 68 | ### 4. Permanent Ban 69 | 70 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 71 | 72 | **Consequence**: A permanent ban from any sort of public interaction within the community. 73 | 74 | ## Attribution 75 | 76 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 77 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 78 | 79 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 80 | 81 | [homepage]: https://www.contributor-covenant.org 82 | 83 | For answers to common questions about this code of conduct, see the FAQ at 84 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 85 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source "https://rubygems.org" 4 | 5 | # Specify your gem's dependencies in async_scheduler.gemspec 6 | gemspec 7 | 8 | gem "rake", "~> 13.0" 9 | 10 | gem "rspec", "~> 3.0" 11 | 12 | gem "rubocop", "~> 1.21" 13 | 14 | # TODO: Remove gems below before releasing! 15 | gem 'pry' 16 | gem 'pry-doc' 17 | gem 'pry-byebug' 18 | gem 'pry-stack_explorer' 19 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 kudojp 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ⚠️ This project is still work in progress, and not published as a gem yet. 2 | 3 | # AsyncScheduler 4 | 5 | [![CI](https://github.com/kudojp/async_scheduler/actions/workflows/ci.yaml/badge.svg)](https://github.com/kudojp/async_scheduler/actions/workflows/ci.yaml) 6 | [![codecov](https://codecov.io/gh/kudojp/async_scheduler/branch/main/graph/badge.svg?token=1JZU04RYFD)](https://codecov.io/gh/kudojp/async_scheduler) 7 | [![License](https://img.shields.io/github/license/kudojp/async_scheduler)](./LICENSE) 8 | 9 | This is a Fiber Schduler, which is a missing piece to do concurrent programming in Ruby language. 10 | If you are not familiar with the concept of Fiber Schduler, please refer to my presentation: [Ruby の FiberScheduler を布教したい](https://speakerdeck.com/kudojp/ruby-false-fiberscheduler-wobu-jiao-sitai). (Sorry in Japanese.) 11 | 12 | 13 | ## Installation 14 | 15 | Add this line to your application's Gemfile: 16 | 17 | ```ruby 18 | gem 'async_scheduler' 19 | ``` 20 | 21 | And then execute: 22 | 23 | ``` 24 | $ bundle install 25 | ``` 26 | 27 | Or install it yourself as: 28 | 29 | ``` 30 | $ gem install async_scheduler 31 | ``` 32 | 33 | ## Usage 34 | 35 | Set this scheduler in the current thread. 36 | Then, surround each of blocking oerations in `Fiber.schedule` block so that they are executed concurrently. 37 | 38 | ```rb 39 | Fiber.set_schduler AsyncScheduler::Scheduler.new 40 | 41 | Fiber.schedule do 42 | File.read("file1.txt") # some blocking operation 43 | end 44 | 45 | Fiber.schedule do 46 | File.read("file2.txt") # some blocking operation 47 | end 48 | 49 | puts "Finished" 50 | ``` 51 | 52 | 53 | ## Development 54 | 55 | Add and run spec. 56 | 57 | ``` 58 | bundle exec rspec 59 | ``` 60 | 61 | ## Contributing 62 | 63 | Bug reports and pull requests are welcome on GitHub at https://github.com/kudojp/async_scheduler. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/kudojp/async_scheduler/blob/master/CODE_OF_CONDUCT.md). 64 | 65 | ## License 66 | 67 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 68 | 69 | ## Code of Conduct 70 | 71 | Everyone interacting in the AsyncScheduler project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/async_scheduler/blob/master/CODE_OF_CONDUCT.md). 72 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "bundler/gem_tasks" 4 | require "rspec/core/rake_task" 5 | 6 | RSpec::Core::RakeTask.new(:spec) 7 | 8 | require "rubocop/rake_task" 9 | 10 | RuboCop::RakeTask.new 11 | 12 | task default: %i[spec rubocop] 13 | -------------------------------------------------------------------------------- /async_scheduler.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "lib/async_scheduler/version" 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = "async_scheduler" 7 | spec.version = AsyncScheduler::VERSION 8 | spec.authors = ["kudojp"] 9 | spec.email = ["heyjudejudejude1968@gmail.com"] 10 | 11 | spec.summary = "Asynchronous task scheduler in Ruby" 12 | spec.description = "This is a task scheduler which implements the FiberScheduler interface" 13 | spec.homepage = "https://github.com/kudojp/async_scheduler" 14 | spec.license = "MIT" 15 | # The interface of FiberScheduler#io_read had a breaking change from Ruby 3.0 to 3.1. 16 | # - Ruby 3.0: #io_read takes 4 arguments. 17 | # - Ruby 3.1: #io_read takes 3 arguments. 18 | # The implementation of scheduler#io_read in this gem takes only 3 arguments. 19 | spec.required_ruby_version = "~> 3.1.0" 20 | 21 | spec.metadata["allowed_push_host"] = "https://rubygems.org" 22 | 23 | spec.metadata["homepage_uri"] = spec.homepage 24 | spec.metadata["source_code_uri"] = "https://github.com/kudojp/async_scheduler" 25 | spec.metadata["changelog_uri"] = "https://github.com/kudojp/async_scheduler/blob/main/CHANGELOG.md" 26 | 27 | # Specify which files should be added to the gem when it is released. 28 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 29 | spec.files = Dir.chdir(File.expand_path(__dir__)) do 30 | `git ls-files -z`.split("\x0").reject do |f| 31 | (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)}) 32 | end 33 | end 34 | spec.bindir = "exe" 35 | spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } 36 | spec.require_paths = ["lib"] 37 | 38 | spec.add_dependency "resolv_fiber", "~>0.1" 39 | 40 | spec.add_development_dependency "simplecov-cobertura" 41 | 42 | # For more information and examples about making a new gem, check out our 43 | # guide at: https://bundler.io/guides/creating_gem.html 44 | end 45 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "bundler/setup" 5 | require "async_scheduler" 6 | 7 | # You can add fixtures and/or initialization code here to make experimenting 8 | # with your gem easier. You can also use a different console, if you like. 9 | 10 | require "pry" 11 | Pry.start 12 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /codecov.yaml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: 4 | default: 5 | target: 30% 6 | patch: false 7 | -------------------------------------------------------------------------------- /lib/async_scheduler.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "async_scheduler/version" 4 | require_relative "async_scheduler/scheduler" 5 | 6 | module AsyncScheduler 7 | end 8 | -------------------------------------------------------------------------------- /lib/async_scheduler/cross_thread_usage_detector.rb: -------------------------------------------------------------------------------- 1 | module CrossThreadUsageDetector 2 | class BelongingThreadAlreadySetError < StandardError; end 3 | class CrossThreadUsageError < StandardError; end 4 | 5 | def set_belonging_thread! 6 | if defined? @belonging_thread_object_id 7 | raise BelongingThreadAlreadySetError.new("@belonging_thread_object_id is already set with #{@belonging_thread_object_id}, but it is attempted to set again with #{Thread.current.object_id}.") 8 | end 9 | 10 | @belonging_thread_object_id = Thread.current.object_id 11 | end 12 | 13 | def validate_used_in_original_thread! 14 | return if @belonging_thread_object_id == Thread.current.object_id 15 | 16 | raise CrossThreadUsageError.new("Cross-thread usage detected. FiberScheduler was originally registered to a thread (#{@belonging_thread_object_id}), but it is attempted to be used in another thread (#{Thread.current.object_id}).") 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /lib/async_scheduler/scheduler.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | require 'resolv_fiber' 3 | require_relative './cross_thread_usage_detector' 4 | 5 | module AsyncScheduler 6 | # This class implements Fiber::SchedulerInterface. 7 | # See https://ruby-doc.org/core-3.1.0/Fiber/SchedulerInterface.html for details. 8 | class Scheduler 9 | include CrossThreadUsageDetector 10 | 11 | def initialize 12 | set_belonging_thread! 13 | 14 | # (key, value) = (Fiber object, timeout) 15 | @waitings = {} 16 | # (key, value) = (blocking io, Fiber object) 17 | @input_waitings = {} 18 | @output_waitings = {} 19 | # Fibers which are blocking and whose timeouts are not determined. 20 | # e.g. Fiber which includes sleep() 21 | @blockings = Set.new() 22 | # (key, value) = (socket, Hash{:blocked_fiber => , :timeout => }) 23 | @blocking_sockets = {} 24 | # NOTE: When either of the sockets(value) is ready, the fiber(key) can be resumed. 25 | @fiber_to_all_blocker_sockets = Hash.new{|h, fiber| h[fiber] = Set.new} 26 | end 27 | 28 | # Implementation of the Fiber.schedule. 29 | # The method is expected to immediately run the given block of code in a separate non-blocking fiber, 30 | # and to return that Fiber. 31 | def fiber(&block) 32 | validate_used_in_original_thread! 33 | 34 | fiber = Fiber.new(blocking: false, &block) 35 | fiber.resume 36 | fiber 37 | end 38 | 39 | # Invoked by methods like Thread.join, and by Mutex, to signify that current Fiber is blocked until further notice (e.g. unblock) or until timeout has elapsed. 40 | # blocker is what we are waiting on, informational only (for debugging and logging). There are no guarantee about its value. 41 | # Expected to return boolean, specifying whether the blocking operation was successful or not. 42 | def block(blocker, timeout = nil) 43 | validate_used_in_original_thread! 44 | 45 | # TODO: Make use of blocker. 46 | if timeout 47 | @waitings[Fiber.current] = timeout 48 | else 49 | @blockings << Fiber.current 50 | end 51 | 52 | true 53 | end 54 | 55 | # Invoked to wake up Fiber previously blocked with block (for example, Mutex#lock calls block and Mutex#unlock calls unblock). 56 | # The scheduler should use the fiber parameter to understand which fiber is unblocked. 57 | # blocker is what was awaited for, but it is informational only (for debugging and logging), 58 | # and it is not guaranteed to be the same value as the blocker for block. 59 | def unblock(blocker, fiber) 60 | validate_used_in_original_thread! 61 | 62 | # TODO: Make use of blocker. 63 | @blockings.delete fiber 64 | fiber.resume 65 | end 66 | 67 | # Invoked by Kernel#sleep and Mutex#sleep and is expected to provide an implementation of sleeping in a non-blocking way. 68 | # Implementation might register the current fiber in some list of “which fiber wait until what moment”, 69 | # call Fiber.yield to pass control, and then in close resume the fibers whose wait period has elapsed. 70 | def kernel_sleep(duration = nil) 71 | validate_used_in_original_thread! 72 | 73 | timeout = duration ? Process.clock_gettime(Process::CLOCK_MONOTONIC) + duration : nil 74 | if block(:kernel_sleep, timeout) 75 | Fiber.yield 76 | else 77 | raise RuntimeError.new("Failed to sleep") 78 | end 79 | end 80 | 81 | # Invoked by Timeout.timeout to execute the given block within the given duration. 82 | # It can also be invoked directly by the scheduler or user code. 83 | # 84 | # This implementation will only interrupt non-blocking operations. 85 | # If the block is executed successfully, its result will be returned. 86 | def timeout_after(duration, exception_class, *exception_arguments, &block) # → result of block 87 | validate_used_in_original_thread! 88 | 89 | current_fiber = Fiber.current 90 | 91 | if duration 92 | self.fiber() do 93 | sleep(duration) 94 | if current_fiber.alive? 95 | current_fiber.raise(exception_class, *exception_arguments) 96 | end 97 | end 98 | end 99 | 100 | yield duration 101 | end 102 | 103 | # Called when the current thread exits. The scheduler is expected to implement this method in order to allow all waiting fibers to finalize their execution. 104 | # The suggested pattern is to implement the main event loop in the close method. 105 | def close 106 | validate_used_in_original_thread! 107 | 108 | while !@waitings.empty? || !@blockings.empty? || !@input_waitings.empty? || !@output_waitings.empty? || !@blocking_sockets.empty? 109 | # For blocking I/Os... 110 | while !@input_waitings.empty? || !@output_waitings.empty? || !@blocking_sockets.empty? 111 | soonest_timeout_ = self.soonest_timeout 112 | select_duration = 113 | if soonest_timeout_.nil? 114 | nil 115 | else 116 | duration = soonest_timeout_ - Process.clock_gettime(Process::CLOCK_MONOTONIC) 117 | # duration here should be very close to 0 even if it is negative. 118 | [duration, 0].max 119 | end 120 | 121 | # NOTE: IO.select will keep blocking until timeout even if any new event is added to @waitings. 122 | # TODO: Don't wait for the input ready when the corresponding fiber gets terminated, and when it is the only one in @input_waitings. 123 | # TODO: Don't wait for the output ready when the corresponding fiber gets terminated, and when it is the only one in @output_waitings. 124 | inputs_ready, outputs_ready = IO.select( 125 | @input_waitings.keys + @blocking_sockets.keys, 126 | @output_waitings.keys, 127 | [], 128 | select_duration 129 | ) 130 | 131 | inputs_ready&.each do |input| 132 | if @input_waitings[input] 133 | fiber_non_blocking = @input_waitings.delete(input) 134 | fiber_non_blocking.resume if fiber_non_blocking.alive? 135 | elsif @blocking_sockets[input] 136 | fiber = @blocking_sockets.delete(input).fetch(:blocked_fiber) 137 | # ref. comment in #address_resolve 138 | @fiber_to_all_blocker_sockets.fetch(fiber).each do |socket| 139 | @blocking_sockets.delete(socket) 140 | end 141 | fiber.resume 142 | else 143 | raise 144 | end 145 | end 146 | 147 | current_clock_monotonic_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) 148 | 149 | timeout_sockets = @blocking_sockets.select{|socket, blocked| blocked.fetch(:timeout) && (blocked.fetch(:timeout) <= current_clock_monotonic_time)}.keys 150 | # NOTE: timeout_sockets is nil when there is no rejected element. 151 | @blocking_sockets.reject!{|socket| timeout_sockets&.include? socket} 152 | timeout_sockets&.each do |socket| 153 | @fiber_to_all_blocker_sockets.fetch(fiber).delete(socket) 154 | fiber.resume if @fiber_to_all_blocker_sockets.fetch(fiber).empty? && fiber.alive? 155 | end 156 | 157 | outputs_ready&.each do |output| 158 | fiber_non_blocking = @output_waitings.delete(output) 159 | fiber_non_blocking.resume if fiber_non_blocking.alive? 160 | end 161 | end 162 | 163 | unless @waitings.empty? 164 | # TODO: Use a min heap for @waitings 165 | resumable_fibers = @waitings.select{|_fiber, timeout| timeout <= Process.clock_gettime(Process::CLOCK_MONOTONIC)} 166 | .map{|fiber, _timeout| fiber} 167 | .to_set 168 | resumable_fibers.each{|fiber| fiber.resume if fiber.alive?} 169 | @waitings.reject!{|fiber, _timeout| resumable_fibers.include? fiber} 170 | end 171 | 172 | # Unfortunately, current scheduler is unfair to @blockings. Even if any of @blockings is ready, current scheduler has no way to notice it. 173 | @blockings.select!{|fiber| fiber.alive?} 174 | end 175 | end 176 | 177 | def soonest_timeout 178 | waitings_earliest_timeout = @waitings.empty? ? nil : @waitings.min_by{|fiber, timeout| timeout}[1] 179 | blocking_socket_earliest_timeout = @blocking_sockets.select{|_socket, blocked| blocked.fetch(:timeout)}.values.min_by{|blocked| blocked.fetch(:timeout)}[0]&.fetch(:timeout) 180 | 181 | if waitings_earliest_timeout && blocking_socket_earliest_timeout 182 | return [waitings_earliest_timeout, blocking_socket_earliest_timeout].min 183 | end 184 | 185 | waitings_earliest_timeout || blocking_socket_earliest_timeout 186 | end 187 | private_methods :soonest_timeout 188 | 189 | # Invoked by IO#wait, IO#wait_readable, IO#wait_writable to ask whether the specified descriptor is ready for specified events within the specified timeout. 190 | # events is a bit mask of IO::READABLE, IO::WRITABLE, and IO::PRIORITY. 191 | 192 | # Suggested implementation should register which Fiber is waiting for which resources and immediately calling Fiber.yield to pass control to other fibers. 193 | # Then, in the close method, the scheduler might dispatch all the I/O resources to fibers waiting for it. 194 | # Expected to return the subset of events that are ready immediately. 195 | def io_wait(io, events, _timeout) 196 | validate_used_in_original_thread! 197 | 198 | # TODO: use timeout parameter 199 | # TODO?: Expected to return the subset of events that are ready immediately. 200 | 201 | if events & IO::READABLE == IO::READABLE 202 | @input_waitings[io] = Fiber.current 203 | end 204 | 205 | if events & IO::WRITABLE == IO::WRITABLE 206 | @output_waitings[io] = Fiber.current 207 | end 208 | 209 | Fiber.yield 210 | end 211 | 212 | # Invoked by IO#read to read length bytes from io into a specified buffer (see IO::Buffer). 213 | # The length argument is the “minimum length to be read”. If the IO buffer size is 8KiB, but the length is 1024 (1KiB), up to 8KiB might be read, but at least 1KiB will be. 214 | # Generally, the only case where less data than length will be read is if there is an error reading the data. 215 | # Specifying a length of 0 is valid and means try reading at least once and return any available data. 216 | 217 | # Suggested implementation should try to read from io in a non-blocking manner and call io_wait if the io is not ready (which will yield control to other fibers). 218 | # See IO::Buffer for an interface available to return data. 219 | # Expected to return number of bytes read, or, in case of an error, -errno (negated number corresponding to system's error code). 220 | def io_read(io, buffer, length) # return length or -errno 221 | validate_used_in_original_thread! 222 | 223 | read_string = "" 224 | offset = 0 225 | while offset < length || length == 0 226 | read_nonblock = Fiber.new(blocking: true) do 227 | # AsyncScheduler::Scheduler#io_read is hooked to IO#read_nonblock. 228 | # To avoid an infinite call loop, IO#read_nonblock is called inside a Fiber whose blocking=true. 229 | # ref. https://docs.ruby-lang.org/ja/latest/method/IO/i/read_nonblock.html 230 | io.read_nonblock(buffer.size-offset, read_string, exception: false) 231 | end 232 | 233 | begin 234 | # This fiber is resumed only here. 235 | result = read_nonblock.resume 236 | rescue SystemCallError => e 237 | return -e.errno 238 | end 239 | 240 | case result 241 | when :wait_readable 242 | io_wait(io, IO::READABLE, nil) 243 | when nil # when reaching EOF 244 | # TODO: Investigate if it is expected to break here. 245 | break 246 | else 247 | offset += buffer.set_string(read_string, offset) # this does not work with `#set_string(result)` 248 | break if length == 0 249 | end 250 | end 251 | return offset 252 | end 253 | 254 | # Invoked by IO#write to write length bytes to io from from a specified buffer (see IO::Buffer). 255 | # The length argument is the “(minimum) length to be written”. 256 | # If the IO buffer size is 8KiB, but the length specified is 1024 (1KiB), at most 8KiB will be written, but at least 1KiB will be. 257 | # Generally, the only case where less data than length will be written is if there is an error writing the data. 258 | 259 | # Specifying a length of 0 is valid and means try writing at least once, as much data as possible. 260 | # Suggested implementation should try to write to io in a non-blocking manner and call io_wait if the io is not ready (which will yield control to other fibers). 261 | # See IO::Buffer for an interface available to get data from buffer efficiently. 262 | # Expected to return number of bytes written, or, in case of an error, -errno (negated number corresponding to system's error code). 263 | def io_write(io, buffer, length) # returns: written length or -errnoclick to toggle source 264 | validate_used_in_original_thread! 265 | 266 | offset = 0 267 | 268 | while offset < length || length == 0 269 | write_nonblock = Fiber.new(blocking: true) do 270 | # TODO: Investigate if this #write_nonblock method call should be in a non-blocking fiber. 271 | # IO#read_nonblock is hooked to Scheduler#io_wait, so it has to be wrapped. 272 | # If IO#read_nonblock is hooked to Scheduler#io_read, this method call has to be wrapped too. 273 | # ref. https://docs.ruby-lang.org/ja/latest/class/IO.html#I_WRITE_NONBLOCK 274 | io.write_nonblock(buffer.get_string(offset), exception: false) 275 | end 276 | 277 | begin 278 | result = write_nonblock.resume 279 | rescue SystemCallError => e 280 | return -e.errno 281 | end 282 | 283 | case result 284 | when :wait_writable 285 | io_wait(io, IO::WRITABLE, nil) 286 | else 287 | offset += result 288 | break if length == 0 # Specification says it tries writing at least once if length == 0 289 | end 290 | end 291 | return offset 292 | end 293 | 294 | # Invoked by any method that performs a non-reverse DNS lookup. (e.g. Addrinfo.getaddrinfo) 295 | # The method is expected to return an array of strings corresponding to ip addresses the hostname is resolved to, or nil if it can not be resolved. 296 | def address_resolve(hostname) 297 | # NOTE: 298 | # Asynchronous DNS lookup is slower than sequential DNS lookup in a single thread in my experiment. 299 | # Remove #address_resolve when this scheduler is used in a performance critical application. 300 | # Run $ `bundle exec rspec spec/blockings/address_resolve_spec.rb` to confirm it. 301 | 302 | validate_used_in_original_thread! 303 | fiber = ::ResolvFiber.getaddresses_fiber(hostname) 304 | # Fiber.yield inside of this fiber is located in the loop and may be called multiple times. 305 | # So here in the caller, the fiber has to be resumed multiple times till the fiber becomes terminated. 306 | loop do 307 | result = fiber.resume 308 | return result unless fiber.alive? 309 | 310 | socks, timeout = result 311 | # In my experiment, socks here are: 312 | # - socket to connect to the DNS server which has IPv4 address 313 | # - socket to connect to the DNS server which has IPv6 address 314 | # When either of these is ready, DNS resolution is done. 315 | socks.each do |sock| 316 | # Fiber.current is blocked by multiple sockets in this way: 317 | # @blocking_sockets = { 318 | # first_socket: { blocked_fiber: Fiber.current, timeout: 1111 }, 319 | # second_socket: { blocked_fiber: Fiber.current, timeout: 1111 }, 320 | # } 321 | # If first_socket is ready, both of `first_socket` and `second_socket` must be removed from @blocking_sockets before the fiber gets resumed. 322 | # (@fiber_to_all_blocker_sockets is used to realize this.) 323 | # Otherwise, when second_socket is ready, `Fiber.current` will be resumed again unexpectedly. 324 | # Same thing can be said if second_socket is ready first. 325 | @blocking_sockets[sock] = { 326 | blocked_fiber: Fiber.current, 327 | timeout: timeout, 328 | } 329 | @fiber_to_all_blocker_sockets[Fiber.current] << sock 330 | end 331 | 332 | Fiber.yield 333 | end 334 | end 335 | end 336 | end 337 | -------------------------------------------------------------------------------- /lib/async_scheduler/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module AsyncScheduler 4 | VERSION = "0.1.1" 5 | end 6 | -------------------------------------------------------------------------------- /sig/async_std_scheduler.rbs: -------------------------------------------------------------------------------- 1 | module AsyncScheduler 2 | VERSION: String 3 | # See the writing guide of rbs: https://github.com/ruby/rbs#guides 4 | end 5 | -------------------------------------------------------------------------------- /spec/async_scheduler_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.describe AsyncScheduler do 4 | it "has a version number" do 5 | expect(AsyncScheduler::VERSION).not_to be nil 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/basics/threading_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'async_scheduler/cross_thread_usage_detector' 4 | 5 | RSpec.describe AsyncScheduler do 6 | it "can create and run a new thread in a Fiber.schedule block" do 7 | parent_thread = Thread.new do 8 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 9 | Fiber.schedule do 10 | $child_thread = Thread.new {} 11 | $child_thread.join 12 | end 13 | end 14 | 15 | begin 16 | parent_thread.join 17 | raise Exception.new("This should not be reached") 18 | rescue => e 19 | expect(e.class).to eq(CrossThreadUsageDetector::CrossThreadUsageError) 20 | expect(e.message).to eq("Cross-thread usage detected. FiberScheduler was originally registered to a thread (#{parent_thread.object_id}), but it is attempted to be used in another thread (#{$child_thread.object_id}).") 21 | end 22 | 23 | # NOTE: the reason why I don't use the following code is because: 24 | # `#{$child_thread.object_id}` in the matcher seems to be evaluated before `parent_thread.join` finishes. 25 | # When this occurs, $child_thread.object_id is not set yet and it is evaluated as 8, which is object_id of nil. 26 | # 27 | # expect { parent_thread.join }.to raise_error( 28 | # CrossThreadUsageDetector::CrossThreadUsageError, 29 | # "Cross-thread usage detected. FiberScheduler was originally registered to a thread (#{parent_thread.object_id}), but it is attempted to be used in another thread (#{$child_thread.object_id})." 30 | # ) 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/blockings/address_resolve_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require 'socket' 3 | require 'resolv' 4 | 5 | RSpec.describe AsyncScheduler do 6 | describe "DNS resolution" do 7 | def resolve_address_with_scheduler(hostname, port, family=nil, socket_type=nil) 8 | Thread.new do 9 | scheduler = AsyncScheduler::Scheduler.new 10 | Fiber.set_scheduler scheduler 11 | t = Process.clock_gettime(Process::CLOCK_MONOTONIC) 12 | ips = nil 13 | Fiber.schedule do 14 | ips = Socket.getaddrinfo(hostname, port, family=family, socket_type=socket_type) 15 | end 16 | scheduler.close 17 | puts "Took: #{Process.clock_gettime(Process::CLOCK_MONOTONIC) - t} seconds" 18 | ips 19 | end.value 20 | end 21 | 22 | it "resolves localhost successfully" do 23 | # NOTE: 24 | # Value of Socket::Constants::AF_INET6 seems to differ according to the OS. 25 | # - Ubuntu: 10 26 | # - MacOS: 30 27 | # Thus, it is not hard-coded in tests below. 28 | puts "#### Resolving (localhost, 443)" 29 | expect(resolve_address_with_scheduler("localhost", 443)).to contain_exactly( 30 | ["AF_INET", 443, "127.0.0.1", "127.0.0.1", 2, 1, 6], 31 | ["AF_INET", 443, "127.0.0.1", "127.0.0.1", 2, 2, 17], 32 | ["AF_INET", 443, "127.0.0.1", "127.0.0.1", 2, 3, 0], 33 | ["AF_INET6", 443, "::1", "::1", Socket::Constants::AF_INET6, 1, 6], 34 | ["AF_INET6", 443, "::1", "::1", Socket::Constants::AF_INET6, 2, 17], 35 | ["AF_INET6", 443, "::1", "::1", Socket::Constants::AF_INET6, 3, 0], 36 | ) 37 | puts "### Resolving (localhost, 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_STREAM)" 38 | expect(resolve_address_with_scheduler("localhost", 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_STREAM)).to contain_exactly(["AF_INET", 443, "127.0.0.1", "127.0.0.1", 2, 1, 6]) 39 | puts 40 | puts "### Resolving (localhost, 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_DGRAM)" 41 | expect(resolve_address_with_scheduler("localhost", 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_DGRAM)).to contain_exactly(["AF_INET", 443, "127.0.0.1", "127.0.0.1", 2, 2, 17]) 42 | puts 43 | puts "### Resolving (localhost, 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_RAW)" 44 | expect(resolve_address_with_scheduler("localhost", 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_RAW)).to contain_exactly(["AF_INET", 443, "127.0.0.1", "127.0.0.1", 2, 3, 0]) 45 | puts 46 | puts "### Resolving (localhost, 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_STREAM)" 47 | expect(resolve_address_with_scheduler("localhost", 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_STREAM)).to contain_exactly(["AF_INET6", 443, "::1", "::1", Socket::Constants::AF_INET6, 1, 6]) 48 | puts 49 | puts "### Resolving (localhost, 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_DGRAM)" 50 | expect(resolve_address_with_scheduler("localhost", 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_DGRAM)).to contain_exactly(["AF_INET6", 443, "::1", "::1", Socket::Constants::AF_INET6, 2, 17]) 51 | puts 52 | puts "### Resolving (localhost, 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_RAW)" 53 | expect(resolve_address_with_scheduler("localhost", 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_RAW)).to contain_exactly(["AF_INET6", 443, "::1", "::1", Socket::Constants::AF_INET6, 3, 0]) 54 | puts 55 | end 56 | 57 | it "resolves google.com successfully" do 58 | puts "### Resolving (google.com, 443)" 59 | address_info = resolve_address_with_scheduler("google.com", 443) 60 | print "addresses: ", address_info, "\n\n" 61 | 62 | puts "### Resolving (google.com, 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_STREAM)" 63 | address_info = resolve_address_with_scheduler("google.com", 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_STREAM) 64 | # NOTE: It does not check if this IP is really google.com. 65 | ipv4 = address_info[0][2] 66 | expect(ipv4).to match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) 67 | expect(address_info).to include(["AF_INET", 443, ipv4, ipv4, 2, 1, 6]) 68 | print address_info, "\n\n" 69 | 70 | puts "### Resolving (google.com, 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_DGRAM)" 71 | address_info = resolve_address_with_scheduler("google.com", 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_DGRAM) 72 | ipv4 = address_info[0][2] 73 | expect(ipv4).to match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) 74 | expect(address_info).to include(["AF_INET", 443, ipv4, ipv4, 2, 2, 17]) 75 | print address_info, "\n\n" 76 | 77 | puts "### Resolving (google.com, 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_RAW)" 78 | address_info = resolve_address_with_scheduler("google.com", 443, family=Socket::Constants::AF_INET, socket_type=Socket::Constants::SOCK_RAW) 79 | ipv4 = address_info[0][2] 80 | expect(ipv4).to match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) 81 | expect(address_info).to include(["AF_INET", 443, ipv4, ipv4, 2, 3, 0]) 82 | print address_info, "\n\n" 83 | 84 | puts "### Resolving (google.com, 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_STREAM)" 85 | address_info = resolve_address_with_scheduler("google.com", 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_STREAM) 86 | ipv6 = address_info[0][2] 87 | # NOTE: there could be multiple resolved IPv6 addresses. 88 | expect(address_info).to include(["AF_INET6", 443, ipv6, ipv6, Socket::Constants::AF_INET6, 1, 6]) 89 | print address_info, "\n\n" 90 | 91 | puts "### Resolving (google.com, 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_DGRAM)" 92 | address_info = resolve_address_with_scheduler("google.com", 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_DGRAM) 93 | ipv6 = address_info[0][2] 94 | expect(address_info).to include(["AF_INET6", 443, ipv6, ipv6, Socket::Constants::AF_INET6, 2, 17]) 95 | print address_info, "\n\n" 96 | 97 | puts "### Resolving (google.com, 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_RAW)" 98 | address_info = resolve_address_with_scheduler("google.com", 443, family=Socket::Constants::AF_INET6, socket_type=Socket::Constants::SOCK_RAW) 99 | ipv6 = address_info[0][2] 100 | expect(address_info).to include(["AF_INET6", 443, ipv6, ipv6, Socket::Constants::AF_INET6, 3, 0]) 101 | print address_info, "\n\n" 102 | end 103 | end 104 | 105 | describe "DNS resolution performance" do 106 | def resolve_address_with_scheduler(hostname, port, num_times) 107 | Thread.new do 108 | scheduler = AsyncScheduler::Scheduler.new 109 | Fiber.set_scheduler scheduler 110 | t = Process.clock_gettime(Process::CLOCK_MONOTONIC) 111 | 112 | num_times.times do 113 | Fiber.schedule do 114 | Socket.getaddrinfo("www.google.com", 443) 115 | end 116 | end 117 | 118 | scheduler.close 119 | Process.clock_gettime(Process::CLOCK_MONOTONIC) - t 120 | end.value 121 | end 122 | 123 | def resolve_address_sequentially(hostname, port, num_times) 124 | t = Process.clock_gettime(Process::CLOCK_MONOTONIC) 125 | num_times.times do 126 | Socket.getaddrinfo("www.google.com", 443) 127 | end 128 | Process.clock_gettime(Process::CLOCK_MONOTONIC) - t 129 | end 130 | 131 | 132 | def resolve_address_with_multithreads(hostname, port, num_times) 133 | t = Process.clock_gettime(Process::CLOCK_MONOTONIC) 134 | threads = [] 135 | num_times.times do 136 | threads << Thread.new do 137 | Socket.getaddrinfo("www.google.com", 443) 138 | end 139 | end 140 | # NOTE: I could not find how to wait for multiple threads to join in a Promise.all equivalent manner in Ruby. 141 | threads.each(&:join) 142 | Process.clock_gettime(Process::CLOCK_MONOTONIC) - t 143 | end 144 | 145 | it "resolves addresses in a Fiber.schedule block" do 146 | puts "👁 Confirm these things." 147 | puts "- Resolving with scheduler is faster than multithreading." 148 | puts "- Execution times of resolving scheduler do not improve in a liner manner." 149 | 150 | ["localhost", "google.com"].each do |hostname| 151 | puts "--------------------------" 152 | puts "| Resolve #{hostname.ljust(10)} |" 153 | puts "--------------------------" 154 | 155 | [1, 10, 100].each do |num_times| 156 | puts "## Resolving #{num_times} times:" 157 | puts "Resolve with scheduler: #{resolve_address_with_scheduler(hostname, 443, num_times)}" 158 | puts "Revolve sequentially in a single thread: #{resolve_address_sequentially(hostname, 443, num_times)}" 159 | puts "Resolve with multithreads: #{resolve_address_with_multithreads(hostname, 443, num_times)}" 160 | puts 161 | end 162 | end 163 | end 164 | end 165 | end 166 | -------------------------------------------------------------------------------- /spec/blockings/read_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.describe AsyncScheduler do 4 | before do 5 | File.open("./log1.txt", "w"){|f| f.write("log1") } 6 | File.open("./log2.txt", "w"){|f| f.write("log2") } 7 | File.open("./log3.txt", "w"){|f| f.write("log3") } 8 | end 9 | 10 | it "reads in fibers with AsyncScheduler::Scheduler" do 11 | t = Time.now 12 | thread = Thread.new do 13 | t = Time.now 14 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 15 | 16 | Fiber.schedule do 17 | f1 = File.open("./log1.txt", "r"){|f| f.read() } 18 | # puts '## finished reading in the first fiber: ' 19 | # puts f1 20 | end 21 | Fiber.schedule do 22 | f2 = File.open("./log2.txt", "r"){|f| f.read() } 23 | # puts '## finished reading in the second fiber' 24 | # puts f2 25 | end 26 | Fiber.schedule do 27 | f3 = File.open("./log3.txt", "r"){|f| f.read() } 28 | # puts '## finished reading in the third fiber' 29 | # puts f3 30 | end 31 | 32 | end 33 | thread.join 34 | puts "It took #{Time.now - t} seconds to run three fibers concurrently." 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /spec/blockings/sleep_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.describe AsyncScheduler do 4 | before do 5 | end 6 | 7 | it "sleeps in fibers with AsyncScheduler::Scheduler" do 8 | t = Time.now 9 | thread = Thread.new do 10 | t = Time.now 11 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 12 | 13 | Fiber.schedule do 14 | sleep(3) 15 | end 16 | Fiber.schedule do 17 | sleep(3) 18 | end 19 | Fiber.schedule do 20 | sleep(3) 21 | end 22 | 23 | end 24 | thread.join 25 | # This method should take around 3 seconds, not around 9 seconds. 26 | puts "It took #{Time.now - t} seconds to run three fibers concurrently." 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /spec/blockings/timeout_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require 'timeout' 3 | 4 | RSpec.describe AsyncScheduler do 5 | class CustomTimeoutError < StandardError; end 6 | describe "Timeout.timeout() called asynchronously" do 7 | context "when Timeout.timeout is called with duration which is longer than the block execution time" do 8 | it "returns the return value of the block" do 9 | thread = Thread.new do 10 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 11 | Fiber.schedule do 12 | t = Time.now 13 | timeout_error_message = "timeout!" 14 | expect( 15 | Timeout.timeout(1, CustomTimeoutError, timeout_error_message) do 16 | sleep(0.5) 17 | break 12 18 | end 19 | ).to eq(12) 20 | end 21 | end 22 | thread.join 23 | end 24 | end 25 | 26 | context "when Timeout.timeout is called with duration which is shorter than the block execution time" do 27 | ### This test case is skipped for now because this spec should last forever. 28 | ### Uncomment and confirm it if related changes are made. 29 | # 30 | # context "when block execution time is eternal" do 31 | # it "raises an error as specified with arguments" do 32 | # thread = Thread.new do 33 | # Fiber.set_scheduler AsyncScheduler::Scheduler.new 34 | # Fiber.schedule do 35 | # t = Time.now 36 | # timeout_error_message = "timeout!" 37 | # expect{ 38 | # Timeout.timeout(nil, CustomTimeoutError, timeout_error_message) do 39 | # sleep() 40 | # end 41 | # }.to raise_error(CustomTimeoutError, timeout_error_message) 42 | # end 43 | # end 44 | # thread.join 45 | # end 46 | # end 47 | 48 | context "when block execution time is specified" do 49 | it "raises an error as specified with arguments" do 50 | thread = Thread.new do 51 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 52 | Fiber.schedule do 53 | t = Time.now 54 | timeout_error_message = "timeout!" 55 | expect{ 56 | Timeout.timeout(0.5, CustomTimeoutError, timeout_error_message) do 57 | sleep(1) 58 | end 59 | }.to raise_error(CustomTimeoutError, timeout_error_message) 60 | end 61 | end 62 | thread.join 63 | end 64 | end 65 | end 66 | 67 | context "when Timeout.timeout is called with nil as the duration" do 68 | it "returns the return value of the block" do 69 | thread = Thread.new do 70 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 71 | Fiber.schedule do 72 | t = Time.now 73 | timeout_error_message = "timeout!" 74 | expect( 75 | Timeout.timeout(nil, CustomTimeoutError, timeout_error_message) do 76 | sleep(0.5) 77 | break 12 78 | end 79 | ).to eq(12) 80 | end 81 | end 82 | thread.join 83 | end 84 | end 85 | end 86 | end 87 | -------------------------------------------------------------------------------- /spec/blockings/write_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.describe AsyncScheduler do 4 | before do 5 | File.delete("./log1.txt") 6 | File.delete("./log2.txt") 7 | File.delete("./log3.txt") 8 | end 9 | 10 | it "writes in fibers with AsyncScheduler::Scheduler" do 11 | t = Time.now 12 | thread = Thread.new do 13 | t = Time.now 14 | Fiber.set_scheduler AsyncScheduler::Scheduler.new 15 | 16 | Fiber.schedule do 17 | File.open("./log1.txt", "w"){|f| f.write("aaa") } 18 | # puts '## finished writing in the first fiber' 19 | end 20 | Fiber.schedule do 21 | File.open("./log2.txt", "w"){|f| f.write("bbb") } 22 | # puts '## finished writing in the second fiber' 23 | end 24 | Fiber.schedule do 25 | File.open("./log3.txt", "w"){|f| f.write("ccc") } 26 | # puts '## finished writing in the third fiber' 27 | end 28 | 29 | end 30 | thread.join 31 | puts "It took #{Time.now - t} seconds to run three fibers concurrently." 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | if ENV['CI'] 4 | require "simplecov" 5 | SimpleCov.start do 6 | add_filter '/spec/' 7 | end 8 | 9 | require "simplecov-cobertura" 10 | SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter 11 | end 12 | 13 | require "async_scheduler" 14 | 15 | RSpec.configure do |config| 16 | # Enable flags like --only-failures and --next-failure 17 | config.example_status_persistence_file_path = ".rspec_status" 18 | 19 | # Disable RSpec exposing methods globally on `Module` and `main` 20 | config.disable_monkey_patching! 21 | 22 | config.expect_with :rspec do |c| 23 | c.syntax = :expect 24 | end 25 | end 26 | --------------------------------------------------------------------------------