通过红宝石过程共享变量 [英] Share variable through ruby processes

查看:72
本文介绍了通过红宝石过程共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个gem,在这里我必须派生两个启动两个Webrick服务器的进程.我想通过基类中的类方法启动这些服务器,因为应该只运行这两个服务器,而不是多个服务器.在运行时,我想在这两个服务器上调用一些方法来更改变量.

I'm writing a gem, where I have to fork two processes which are starting two webrick servers. I want to start this servers through a class method from a base class, because there should only be this two servers running, not multiple ones. During runtime, I want to call some methods on this two servers to change variables.

我的问题是,我无法通过基类的类方法访问fork的实例变量.此外,我不能在基类中使用线程,因为在后台,我正在使用另一个不是线程安全的库.因此,我必须将每个服务器分叉到它自己的进程中.

My problem is, that I can't access the instance variables of the forks, through a class method of the base class. Furthermore, I can't use threads inside my base class, because under the hood I'm using another library which is not thread safe. So I have to fork each server to it's own process.

我使用类变量(例如@@server)进行了尝试.但是,当我尝试通过基类访问此变量时,它是nil.我读到在Ruby中无法在fork之间共享类变量,对吗?

I tried it with class variables, like @@server. But when I try to access this variables through the base class, it's nil. I read that sharing class variables among forks isn't possible in Ruby, am I right?

那么,还有其他解决方法吗?我曾考虑过使用单例,但是我不确定这是否是最好的主意.

So, is there any other way around this? I thought of using a singleton, but I'm not sure if this is the best idea.

推荐答案

在派生一个进程时,子进程和父进程的内存是分开的,因此不能直接在它们之间共享变量.因此,单例课程在您的情况下不起作用.

When you fork a process then the child and parent processes's memory are separated, so you cannot share variables between them directly. So a singleton class will not work in your case.

解决方案是 IPC ,Ruby既支持分布式对象.更加透明的界面.

The solution is IPC, Ruby supports both pipes and sockets, which are the two most used forms of IPC, at least on *NIX. Ruby also supports distributed objects, if you need a more transparent interface.

您选择的内容取决于工作.如果您知道要在某个时候将进程拆分到多台计算机上,请使用套接字或drb.如果不行,则使用管道.

What you chose depends on the job. If you know you want to split you processes over several computers at some point, go with sockets or drb. If not go with pipes.

这是对Ruby中管道的简短介绍

这篇关于通过红宝石过程共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆