Ruby-不可变对象 [英] Ruby - Immutable Objects

查看:70
本文介绍了Ruby-不可变对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Ruby编写的高度多线程的应用程序,它共享一些实例变量.对这些变量的写操作很少(占1%),而读操作却很常见(占99%). 确保您的线程始终看到所涉及的最新值的最佳方法是什么(以您的观点还是以惯用的Ruby方式)?尽管我想在大修之前输入您的意见):

I've got a highly multithreaded app written in Ruby that shares a few instance variables. Writes to these variables are rare (1%) while reads are very common (99%). What is the best way (either in your opinion or in the idiomatic Ruby fashion) to ensure that these threads always see the most up-to-date values involved? Here's some ideas so far that I had (although I'd like your input before I overhaul this):

  • 在读取或写入任何这些变量之前,拥有最常用的锁(来自 Java并发实践).这样做的缺点是,它在我的代码中放置了许多synchronize块,但我看不到一种简单的方法来避免这种情况.
  • 使用Ruby的freeze方法(请参见此处),尽管它看起来同样麻烦且没有给我第一个选项带来的同步优势.
  • Have a lock that most be used before reading or writing any of these variables (from Java Concurrency in Practice). The downside of this is that it puts a lot of synchronize blocks in my code and I don't see an easy way to avoid it.
  • Use Ruby's freeze method (see here), although it looks equally cumbersome and doesn't give me any of the synchronization benefits that the first option gives.

这两个选项看起来都很相似,但希望那里的任何人都会有更好的主意(或可以为其中一种主意辩护).我也可以将对象设置为不可变的,这样它们就不会在操作过程中被破坏或更改,但是我对Ruby的了解并不足够,无法凭自己和

These options both seem pretty similar but hopefully anyone out there will have a better idea (or can argue well for one of these ideas). I'd also be fine with making the objects immutable so they aren't corrupted or altered in the middle of an operation, but I don't know Ruby well enough to make the call on my own and this question seems to argue that objects are highly mutable.

推荐答案

使用锁是最合适的方法.您可以看到Jim Weirich的以下主题演讲:所有Rubyist应该了解的关于线程的知识.

Using the lock is the most appropiate way to do this. You can see this presentation by Jim Weirich on the subject: What All Rubyist Should Know About Threading.

此外,冻结对象对您无济于事,因为您要修改这些变量.将它们冻结就位意味着没有进一步的修改将适用于这些(因此,您写入的1%无效).

Also, freezing an object won't help you here since you want to modify these variables. Freezing them in place means that no further modifications will be applicable to these (and therefore your 1% of writes won't work).

这篇关于Ruby-不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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