I have a Ruby program that loads up two very large yaml files, so I can get some speed-up by taking advantage of the multiple cores by forking off some processes. I’ve tried looking, but I’m having trouble figuring how, or even if, I can share variables in different processes.
The following code is what I currently have:
@proteins = ""
@decoyProteins = ""
fork do
@proteins = YAML.load_file(database)
exit
end
fork do
@decoyProteins = YAML.load_file(database)
exit
end
p @proteins["LVDK"]
P displays nil though because of the fork.
So is it possible to have the forked processes share the variables? And if so, how?
One problem is you need to use
Process.waitto wait for your forked processes to complete. The other is that you can’t do interprocess communication through variables. To see this:One way to do interprocess communication is using a pipe (
IO::pipe). Open it before you fork, then have each side of the fork close one end of the pipe.From
ri IO::pipe:If you want to share variables, use threads:
However, I’m not sure if threading will get you any gain when you’re IO bound.