From simon.urbanek at r-project.org  Wed Sep 29 19:57:55 2010
From: simon.urbanek at r-project.org (Simon Urbanek)
Date: Wed, 29 Sep 2010 13:57:55 -0400
Subject: [Rd] checking user interrupts in C(++) code
In-Reply-To: <AANLkTim-qxP3zZmmUpkQQc8Ztk4AERhpyokgAua36Lk2@mail.gmail.com>
References: <AANLkTikfpH46Jb7WF3b1Wv_tMs30vagvx2ZB1dKnu38k@mail.gmail.com>
	<C5CD55A5-2313-4748-8F7F-CFB27136A22F@r-project.org>
	<AANLkTim-qxP3zZmmUpkQQc8Ztk4AERhpyokgAua36Lk2@mail.gmail.com>
Message-ID: <197E5670-F949-4493-8BDC-E2ED219966E0@r-project.org>


On Sep 29, 2010, at 4:31 AM, Karl Forner wrote:

> Hi,
> 
> 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.

Cheers,
Simon



[Rd] checking user interrupts in C(++) code
Simon Urbanek