Multi-Threading question in Objective-C 2.0

前端 未结 3 1923
Happy的楠姐
Happy的楠姐 2021-02-11 05:35

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 get

3条回答
  •  遥遥无期
    2021-02-11 06:10

    If you simply need to protect a critical section of code, why not using the Objective-C @synchronized directive? Of course, using NSLock will also work, but you need to explicitly manage the NSLock instance. From the documentation:

    Objective-C supports multithreading in applications. This means that two threads can try to modify the same object at the same time, a situation that can cause serious problems in a program. To protect sections of code from being executed by more than one thread at a time, Objective-C provides the @synchronized() directive.

    The @synchronized()directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code; that is, when execution continues past the last statement in the @synchronized() block.

    The @synchronized() directive takes as its only argument any Objective-C object, including self. This object is known as a mutual exclusion semaphore or mutex. It allows a thread to lock a section of code to prevent its use by other threads. You should use separate semaphores to protect different critical sections of a program. It’s safest to create all the mutual exclusion objects before the application becomes multithreaded to avoid race conditions.

    Listing 12-1 shows an example of code that uses self as the mutex to synchronize access to the instance methods of the current object. You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self. In the latter case, of course, only one thread at a time is allowed to execute a class method because there is only one class object that is shared by all callers.

    Listing 12-1 Locking a method using self

    - (void)criticalMethod
    {
        @synchronized(self) {
            // Critical code.
            ...
        }
    }
    

提交回复
热议问题