This article is mainly about iOS multi-threading, thread synchronization three ways, more iOS technical knowledge, please visit the website of Crazy software education.
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. And then give this genus
The value corresponding to the sexual assignment. 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 is wired
The lock flag of the object inside the brackets will be locked, and the other thread will open the other thread when the thread is out.
Go in one more. 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:
[Objc]view plaincopyprint? To view code slices from the tag to my Code slice
-(void) selltickets{
while (YES) {
NSString *name = [Nsthread currentthread].name;
Synchronizing code blocks when a thread goes in, it locks the lock flag of the object inside the parentheses, and the other threads wait outside to get in.
When we go out, we open the locks, and the rest of the threads go into one
@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];
}
// }
}
IOS Multi-threading, three ways to thread sync