Question

If two threads call one function "simultaneously," do variables local to the function (not ivars) need to be protected in a mutex/synchronization block to keep other threads from altering/munging them?

Or, does each thread get its own copy of the local variables on the stack, like a recursive call would/should?

Use the extremely fake and pointless function below as an example of what I'm not sure is thread-safe:

- (TicketResponseObj *)createTicketResponse:(NSHTTPURLResponse *)httpResponse {

    //local variable declaration and assignment
    NSInteger localVar_RespCode = [httpResponse statusCode]; 

    //local object ptr declaration, obj allocation, and ptr assignment
    TicketResponseObj *localObj_TicketResponse = [[TicketResponseObj alloc] initWithCode:localVar_RespCode];

    //return ptr to instance of local object
    return localObj_TicketResponse;
}

Please assume that TicketResponseObj's initWithCode is threadsafe. I'm using LLVM-GCC 4.2 as my compiler, and I'm targeting the armv7 architecture. (This example function could easily be static too, if that matters?)

Sorry, I know this is potentially a stupid question, but my friend suggested the answer depends entirely on the compiler/architecture, etc.

Thanks for your help and patience!

Was it helpful?

Solution

No, they do not need to be synchronized. Local variables and variable references exist on the stack, and as such each thread maintains its own stack. The runtime already takes care of allowing concurrent access to the heap allocator, for cases of alloc and new.

OTHER TIPS

Each thread gets its own copy of the local variables on the stack, like a recursive call would.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top