When I was writing an extension of Ruby in C, I started to notice the keyword volatile
.
volatile
?volatile
isn't really taken care of even if you're usually programming in C or C ++. These are basically related to the interaction with ** outside the program **. To put it simply, the effect is that "reading and writing to the destination with volatile
will be performed exactly as written in the program. " In other words, to prevent optimizations such as "I'm writing many times in a row, so I'll only do it the last time" or "I'm reading without changing anything in the code, so I'll cut off the reading". Become. this is,
It is a convenient mechanism for handling (There is also more detailed article).
That said, Ruby doesn't have direct access to the hardware. If so, it means "external work", but what is it?
Ruby has a garbage collector, which is implemented at the base C language level. And this garbage collector will not be garbage collected by simply putting the handle [^ 1] VALUE
of the Ruby object in the register or stack, not only in a special area.
However, if the area is not taken as a variable, that is also useless. So, volatile VALUE
will appear frequently to force you to reserve space as a variable.
However, there are still some parts that cannot be covered. Normally, there is no problem because VALUE
is routed around, but if you take out the pointer of the contents with a character string etc. and use only that, after the last reference to VALUE
(in C language) ) It may happen that the VALUE
variable becomes unnecessary and is overwritten by another one and becomes a prey to the garbage collector (Example. /2012/04/ruby-garbage-collection-exerb-ruby.html)). In such a case, write RB_GC_GUARD (VALUE variable)
after the part that requires VALUE
so that VALUE
will survive up to that point [^ 2].
Even in the world of C extension, "ease of writing" as the idea of Ruby is still alive, but I think that the conflict with the darkness of C language is also an undeniable aspect.
[^ 1]: There are some things like Fixnum
, nil
, false
, true
that treat it as a direct value instead of a handle.
[^ 2]: The contents of RB_GC_GUARD
include" passing VALUE
to a function whose optimization is suppressed by compiler-specific notation" and "writing VALUE
to a volatile
external variable". It was.
Recommended Posts