Skip to content

Ruby 4 Ractor::Port::receive #451

@uu27183141

Description

@uu27183141

Hi.

I'm newbie for Ruby and I'm trying coroutine like something using Async and Ractor::Port.

# frozen_string_literal: true

require "async"

def f
  Async do
    n = Time.now
    Async do
      puts "async 1 before #{Time.now - n}"
      sleep(0.5)
      puts "async 1 after #{Time.now - n}"
    end
    Async do
      puts "async 2 before #{Time.now - n}"
      sleep(1)
      puts "async 2 after #{Time.now - n}"
    end
  end
end

def g
  port = Ractor::Port.new
  Ractor.new port do |port|
    Async do
      sleep(1)
      port.send(:message)
    end
  end
  Async do
    n = Time.now
    Async do
      puts "async 1 before #{Time.now - n}"
      sleep(0.5)
      puts "async 1 after #{Time.now - n}"
    end
    Async do
      puts "async 2 before #{Time.now - n}"
      port.receive
      puts "async 2 after #{Time.now - n}"
    end
  end
end
~/.../ruby/my_gem_r4 $

and output is

[85] pry(main)> f
async 1 before 5.5424e-05
async 2 before 0.00047027
async 1 after 0.501706423
async 2 after 1.000711154
=> #<Async::Task:0x0000000000000688>
[86] pry(main)> g
async 1 before 0.000104577
async 2 before 0.000488231
async 2 after 1.001955307
async 1 after 1.002924576
=> #<Async::Task:0x0000000000000690>
[87] pry(main)>

But, I expected another result like below

[85] pry(main)> f
async 1 before 5.5424e-05
async 2 before 0.00047027
async 1 after 0.501706423
async 2 after 1.000711154
=> #<Async::Task:0x0000000000000688>
[86] pry(main)> g
async 1 before 0.000104577
async 2 before 0.000488231
async 1 after 0.502034231
async 2 after 1.002924576
=> #<Async::Task:0x0000000000000690>
[87] pry(main)>

That part that I think as a problem is output async 1 after's time difference.

Below is Gemfile.

# frozen_string_literal: true

# https://andycroll.com/ruby/read-ruby-version-in-your-gemfile/
# https://rubydoc.info/github/rubygems/rubygems/Gem/Version
ruby "~> 4.0.0"

source "https://rubygems.org"

# Specify your gem's dependencies in my_gem_r4.gemspec
gemspec

gem "rake", "~> 13.0"

gem "minitest", "~> 5.16"

gem "standard", "~> 1.54"

gem "pry", "~> 0.16.0"

gem "pry-reload", "~> 0.3"

gem "async", "~> 2.38", ">= 2.38.1"

Below is ruby version info.

~/.../ruby/my_gem_r4 $ ruby --version
ruby 4.0.2 (2026-03-17 revision d3da9fec82) +PRISM [aarch64-linux-android]

Thanks for read.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions