Shop OBEX P1 Docs P2 Docs Learn Events
Simple question: Passing local variables by address: Is it safe? — Parallax Forums

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

andrewsiandrewsi Posts: 59
edited 2010-11-05 05:58 in Propeller 1
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

Comments

  • kuronekokuroneko Posts: 3,623
    edited 2010-11-05 00:02
    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).
  • localrogerlocalroger Posts: 3,452
    edited 2010-11-05 05:58
    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.
Sign In or Register to comment.