In general, we use threads to access the same piece of resources together across multiple threads. To protect thread resources from the correctness of security and thread access.
In iOS we typically use the following three threads to synchronize code:
The first and second code of the use of synchronization, generally we only need to use Nslock and Nscondition declaration 2 properties. The corresponding value is then assigned to this property. Then it can be used as a threading tool for security control.
It also guarantees the resource security of the thread.
1:nslock Way
[Xxxlock Lock]//Lock
Synchronizing code blocks
[Xxxlock unlock]//unlock
2:nscondition Way
[Xxxcondition Lock]//Lock
Synchronizing code blocks
[Xxxcondition unlock]//unlock
The third way: When using synchronized, in parentheses we normally only need to pass a self. Synchronizing code blocks When the thread goes in, it locks the lock flag of the object inside the brackets, and the other threads will wait outside when the threads go out and lock The rest of the threads into one. This will protect the thread Cheng ask for the security of the resource.
3: @synchronized (same object) {
Thread execution code;
}
Thread resource prevention and control sample code:
<span style= "font-size:10px;" >-(void) selltickets{while (YES) { NSString *name = [nsthread currentthread].name;// Synchronous code block When the thread goes in, it locks the lock flag of the object inside the brackets, and the other thread waits for the threads to go out and locks the rest of the threads into a// @synchronized (self) {// [Self.mylock lock]; [Self.mycondition lock]; NSLog (@ "%@ starts selling%d tickets", name,self.selledcount+1); [Nsthread sleepfortimeinterval:.2]; self.selledcount++; NSLog (@ "%@ sold%d tickets and%d left", name,self.selledcount,self.totalcount-self.selledcount);// [Self.mylock unlock]; [Self.mycondition unlock]; } } }</span>
IOS Multi-threading, three ways to thread sync