Objective-C supports multithreading in applications. Therefore, 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.
@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.
Locking a method using self
- (void)criticalMethod |
{ |
@synchronized(self) { |
// Critical code. |
... |
} |
} |
Locking a method using a custom semaphore
Account *account = [Account accountFromString:[accountField stringValue]]; |
|
// Get the semaphore. |
id accountSemaphore = [Account semaphore]; |
|
@synchronized(accountSemaphore) { |
// Critical code. |
... |
} |