add fork future primitive

This commit is contained in:
2023-02-03 17:02:42 +00:00
parent b276357244
commit b7f33dbe20
2 changed files with 56 additions and 0 deletions

38
app/lib/fork_future.rb Normal file
View File

@@ -0,0 +1,38 @@
class ForkFuture
def initialize(&block)
read, write = ::IO.pipe
@read = read
pid = ::Process.fork do
start = Time.now
read.close
result = block.call
duration = Time.now - start
::Marshal.dump({
duration: duration,
result: result,
}, write)
::Process.exit!(true)
end
write.close
end
def join
wait!
@result[:result]
end
def duration
wait!
@result[:duration]
end
private
def wait!
@result ||= begin
result_buffer = @read.read
@read.close
::Marshal.load(result_buffer)
end
end
end

View File

@@ -0,0 +1,18 @@
require "test_helper"
class ForkFutureTest < ActiveSupport::TestCase
def test_works
captured = "foo"
future1 = ForkFuture.new do
captured + "bar"
end
future2 = ForkFuture.new do
captured + "baz"
end
assert_equal "foobar", future1.join
assert_equal "foobaz", future2.join
assert 0.0 < future1.duration
assert 0.0 < future2.duration
end
end