Reprint please indicate the source: http://blog.csdn.net/zhangxingping
Threads
In addition to providing exception handling mechanisms, OBJECTIVE-C provides thread synchronization capabilities. Exception handling is described in the previous "Exception handling" section.
synchronous execution of Threads
Multithreading in the OBJECTIVE-C support program. This means that two threads are likely to modify the same object at the same time, which can cause serious problems in the program. To avoid the case where multiple threads execute the same piece of code at the same time, Objective-c provides a @synchronized () instruction.
Directive @synchronized () locks the use of a piece of code. Other threads that attempt to execute this piece of code will be blocked until the lock thread exits the code snippet that is protected by the segment, meaning that the last statement in the @synchronized () code block has been executed.
Directive @synchronized () requires a parameter. This parameter can make any Objective-c object, including self. This object is the mutex semaphore. He was able to have a thread protect a piece of code and avoid other threads executing the code. For different key code segments in the program, we should use different semaphores separately. It is safest to avoid competition between threads by creating all the mutex objects that are needed before the application is programmed to execute multithreading.
The code in Listing 12-1 uses self as the mutex semaphore to implement the current object's synchronization of instance method access.
-(void) Criticalmethod
{
@synchronized (self)
{
//critical code;
}
}
Listing 12-2 uses a custom semaphore to lock the method
Account *account = [accountaccoutfromstring: [accountfiled StringValue]];
Gets the semaphore
id accountsemaphore = [account semaphore];
@synchronized (Accountsemaphore)
{
//critical Code
}
The synchronization attribute in the OBJECTIVE-C is supported recursively. A thread can use the same semaphore multiple times in a recursive way; Other threads are blocked knowing that the thread frees up all of its own and the semaphore-related locks, which means that all @synchronized () blocks are exited by normal execution or by exception handling.
When an exception is thrown in the @synchronized () code block, the OBJECTIVE-C runtime catches the exception, releases the semaphore, and throws the exception back to the next exception handler.