[Rd] checking user interrupts in C(++) code
simon.urbanek at r-project.org
Wed Sep 29 19:57:55 CEST 2010
On Sep 29, 2010, at 4:31 AM, Karl Forner wrote:
> Thanks for your reply,
> There are several ways in which you can make your code respond to interrupts properly - which one is suitable depends on your application. Probably the most commonly used for interfacing foreign objects is to create an external pointer with a finalizer - that makes sure the object is released even if you pass it on to R later. For memory allocated within a call you can either use R's transient memory allocation (see Salloc) or use the on.exit handler to cleanup any objects you allocated manually and left over.
> Using R's transient memory allocation is not really an option when you use some code, like a library, not developed for R. Moreover what about c++ and the new operator ?
It's really up to you - clearly, you can set new to use R's allocation (there is some benefit to that due to the more efficient allocation on some platforms, but in general it should not be needed). For the case of a library the other two options I mentioned are more useful.
> One related question: if the code is interrupted, are C++ local objects freed ?
Although this may be compiler-dependent in general the answer is no, because you would have to invoke the C++ clean-up code from on.exit and I'm not aware of a portable way of doing it (but I'm not a C++ expert).
> Otherwise it is very very complex to attack all allocated objects, moreover it depends on where happens the interruption
Yes, but in a well-written C++ code that is usually not a problem because you will have a root object that represents the current operation and thus the cleanup is trivial (you will have a top-level interfacing call anyway). If you have multiple such objects that are hard to track for some reason, you can always use the finalizer approach. As you mentioned yourself the only issue are method-local objects that you cannot move inside of the critical region which you may have to push to the attribute level.
More information about the R-devel