PDA

View Full Version : Simple question: Passing local variables by address: Is it safe?



andrewsi
11-05-2010, 06:49 AM
I am assuming that local variables in a given method live in a fixed location (for the lifetime of the method, anyway) on the stack of the running object, and that they can be passed safely by address to methods in another object (and modified by them), as long as the called method runs in the same cog as the caller.

It seems reasonably safe to assume that doing this to a different cog would be a very bad idea, since there's no guarantee that the passed address would still be valid for that local variable at any point in the future once the call stack has unwound.

If I'm wrong about any of this, please correct me, but all the formal documentation and books on the Prop seem to focus solely on the use of global variables for passing info between objects and doesn't really discuss the safety (or not) of passing local vars to subroutines. I get why using globals is desirable for passing info between cogs (and I'm doing that too), but in my particular project, turning all the local vars into globals would make the list of globals unnecessarily long and unwieldy. The temporary local variables really only need to exist in the context of the method they pertain to, and the synchronous submethods they call which are all running as part of the same cog.

Thanks, and hopefully that wasn't too difficult to parse.
Andy

kuroneko
11-05-2010, 07:02 AM
It's simple really. If you can guarantee that the method owning the local variable(s) exits after the last reader/writer accessed it/them then you're fine. This also means it's not tied to cogs at all as even locals live in hub RAM (stack).

localroger
11-05-2010, 12:58 PM
It's safe but only until the method returns, since local variables are on the stack. So it can pass local variables to child methods by address, but it can only pass them to other cogs if you are extremely certain that the other cog will get and use the data before you return. This could be used for a quick handshake operation such as passing a command to a helper function and waiting for the response, as long as you are sure the other cog will never try to use the address again once you are done with it.