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):
synchronize
blocks in my code and I don't see an easy way to avoid it.freeze
method (see here), although it looks equally cumbersome and doesn't give me any of the synchronization benefits that the first option gives.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.
In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default.
Integers and floats are frozen by default, while booleans are not. So while some primitives are not frozen, Ruby does not provide mutation methods for them and they usually can be treated as immutable objects.
Don't let fancy words confuse you, “mutability” just means that an object's internal state can be changed. This is the default of all objects, excluding those that have been frozen, or those that are part of a list of special objects. In other words, not all objects in Ruby are mutable!
Since all arrays in Ruby are mutable, when we pass the variable some_words (which is a reference to an array) into the method change_the_array , the method actually changes the array! On the other hand, variables bound to objects that are passed by value, like integers, are not mutable.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With