iphoneobjective-ccocoamultithreadingnslock

Multi-Threading question in Objective-C 2.0


I have my main application delegate which contains a method that returns an object. This application delegate runs on the main thread.

I also have a NSOperation that gets run on a different thread. As well as wanting to be able to call my app delegate method on my main thread sometimes, I also need to call it from my NSOperation thread to get the object that it returns. My first question is, if I call this from my other thread...

id newObject = [[[UIApplication sharedApplication] delegate] myMethod];

... will that method be processed on the same thread as the NSOperation, or will it be the same thread (main) as the application delegate is on?

I also want to make sure that the code within myMethod is only called once at a time by either my operation thread or my main thread. Can I just create a NSLock instance var in my application delegate and do something like:

-(id)myMethod {
    [myLock lock];
    myObject = // Get or create my object to return
    [myLock unlock];
    return myObject;
}

Thanks for your help!

Mike


Solution

  • Unless you explicitly write code to cause something to execute on another thread, every method call is going to be executed directly on the thread it was called upon. There is no magic with a method call. You can think of it as having the exact same semantics/ABI as a C function call for the purposes of threading.

    Your locking pattern will work fine to ensure exclusive access across threads.

    Two additional unrelated notes (because so many people trip over it):