IOS multithreading and thread synchronization
Generally, we use threads to access the same resource in multiple threads. To ensure the security of thread resources and ensure the correctness of thread access.
In IOS, we generally use the following three methods to synchronize code:
The first and second types of code are used for synchronization. Generally, we only need to use NSLock and NSCondition to declare two attributes. Then assign the corresponding value to this attribute. As a thread for security prevention and control.
It can also ensure the thread resource security.
1: NSLock Mode
[Xxxlock lock] // lock
Synchronous Code Block
[Xxxlock unlock] // unlock
2: NSCondition Mode
[XxxCondition lock] // lock
Synchronous Code Block
[XxxCondition unlock] // unlock
Method 3: When synchronized is used, we generally only need to pass a self in brackets. When a thread enters the synchronization code block, the lock flag of the object in the brackets will be locked, and other threads will wait for the lock to open the other threads and then enter one. In this way, the security of thread-based question-free resources can be guaranteed.
3: @ synchronized (same object ){
Code execution by thread;
}
Sample Code for thread resource prevention and control:
-(Void) sellTickets {while (YES) {NSString * name = [NSThread currentThread]. name; // Synchronous Code block when a thread goes in, the lock flag of the object in the brackets will be locked, other threads will wait outside. When the threads going in will open the lock and the other threads will enter another // @ synchronized (self) {// [self. myLock lock]; [self. myCondition lock]; NSLog (@ "% @ start to sell the % d ticket", name, self. selledCount + 1); [NSThread sleepForTimeInterval :. 2]; self. selledCount ++; NSLog (@ "% @ sold the % d ticket, with % d tickets left", name, self. selledCount, self. totalCount-self.selledCount); // [self. myLock unlock]; [self. myCondition unlock];} //}