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. |
... |
} |
本文介绍Objective-C中如何使用@synchronized指令保护关键代码段,避免多线程同时修改同一对象导致的问题。通过示例展示了如何利用self及自定义信号量实现线程互斥。
6669

被折叠的 条评论
为什么被折叠?



