Warm tip: This article is reproduced from stackoverflow.com, please click
fork ruby

How to pass back data from forks through memory instead of having to write files in Ruby?

发布于 2020-03-31 22:54:43

I have to stick with MRI Ruby for specific reasons. I need real parallelism instead of the green threads, so I use forks which work great. But I cannot find a way to pass back information from inside the fork processes to the main process through memory instead of having to write data to external files.

How to change data efficiently in the following code? I'd like to add data to the global array from inside the forks:

$data = []

4.times {
    Process.fork {
        $data << rand
    }
}

Process.waitall
p $data

If there is no way to pass data back, then is there any memory cache solution that I can start from Ruby without having to install anything into the underlying operating system? Gems would work for me as well. Thanks.

Questioner
horv77
Viewed
81
horv77 2020-03-31 01:25

Well, I've managed to solve it in a different way using parallel gem:

https://github.com/grosser/parallel

gem install parallel

require "parallel"

# passing data to 3 processes
data = [ 1, 2, 3 ]

result = Parallel.map( data ){|d|
    # some expensive computation ...
    d ** 3
}

p result

[1, 8, 27]