A brief analysis on the communication and thread safety between threads in IOS application development _ios

Source: Internet
Author: User
Tags mutex reserved ticket


Communication between threads

Simple description
Inter-thread communication: In 1 processes, threads are often not isolated, and multiple threads need to communicate frequently

The embodiment of communication between threads
1 Threads passing data to another 1 threads
After performing a specific task in 1 threads, go to another 1 threads to continue the task

Common methods for communication between threads

 code as follows:


-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) wait;
-(void) Performselector: (SEL) aselector onthread: (Nsthread *) THR Withobject: (ID) arg waituntildone: (BOOL) wait;

Sample communication between threads-Picture download










code as follows:

//
Yyviewcontroller.m
06-nsthread04-Communication between threads
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//


#import "YYViewController.h"
@interface Yyviewcontroller ()
@property (Weak, nonatomic) Iboutlet Uiimageview *iconview;
@end


code as follows:

@implementation Yyviewcontroller





-(void) viewdidload
{
[Super Viewdidload];
}



-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
{



Calling the download method in a child thread downloads a picture
[Self performselectorinbackground: @selector (download) Withobject:nil];
}






-(void) Download
{
1. Download the picture according to the URL
Downloading pictures from the network
Nsurl *urlstr=[nsurl urlwithstring:@ "FDSF"];



Convert a picture into binary data
NSData *data=[nsdata datawithcontentsofurl:urlstr];//This line of operations can be time-consuming



Convert the data into pictures
UIImage *image=[uiimage Imagewithdata:data];

2. Go back to the main thread to set the picture
[Self Performselectoronmainthread: @selector (settingimage:) withobject:image Waituntildone:no];
}






Set Display picture
-(void) Settingimage: (UIImage *) image
{
Self.iconview.image=image;
}



@end



Code 2:
 code as follows:

//
Yyviewcontroller.m
06-nsthread04-Communication between threads
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//


#import "YYViewController.h"
#import <NSData.h>

@interface Yyviewcontroller ()
@property (Weak, nonatomic) Iboutlet Uiimageview *iconview;
@end


code as follows:

@implementation Yyviewcontroller





-(void) viewdidload
{
[Super Viewdidload];
}




-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
{
Calling the download method in a child thread downloads a picture



[Self performselectorinbackground: @selector (download) Withobject:nil];
}




-(void) Download
{



1. Download the picture according to the URL
Downloading pictures from the network
Nsurl *urlstr=[nsurl urlwithstring:@ "FDSF"];



Convert a picture into binary data
NSData *data=[nsdata datawithcontentsofurl:urlstr];//This line of operations can be time-consuming



Convert the data into pictures
UIImage *image=[uiimage Imagewithdata:data];



2. Go back to the main thread to set the picture
The first way
[Self Performselectoronmainthread: @selector (settingimage:) withobject:image Waituntildone:no];



The second way
[Self.imageview performselector: @selector (setimage:) onthread:[nsthread Mainthread] Withobject:image Waituntildone:no];



The Third Way
[Self.iconview performselectoronmainthread: @selector (setimage:) withobject:image Waituntildone:no];
}




Set Display picture
-(void) Settingimage: (UIImage *) image
//{
Self.iconview.image=image;
//}



@end






Thread Safety

One, the security hidden trouble of multithreading
resource Sharing
1 of resources may be shared by multiple threads, that is, multiple threads may access the same resource
For example, multiple threads accessing the same object, the same variable, the same file
Data confusion and data security issues can easily be triggered when multiple threads access the same resource
Example one:






Example two:






Problem code:


code as follows:

//
Yyviewcontroller.m
05-Thread Safety
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//



#import "YYViewController.h"

@interface Yyviewcontroller ()
Number of votes remaining

@property (nonatomic,assign) int leftticketscount;
@property (Nonatomic,strong) Nsthread *thread1;
@property (Nonatomic,strong) Nsthread *thread2;
@property (Nonatomic,strong) Nsthread *thread3;


@end

 code as follows:

@implementation Yyviewcontroller






-(void) viewdidload
{
[Super Viewdidload];



By default there are 20 tickets



self.leftticketscount=10;



Open multiple threads, simulate ticket booking



Self.thread1=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];



self.thread1.name=@ "Conductor a";



Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];



self.thread2.name=@ "Conductor B";



Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];
self.thread3.name=@ "Conductor C";
}



&NBSP
-(void) selltickets
{
    while (1) {
        //1. Check the votes first
        int count=self.leftticketscount;
         if (count>0) {
            //Pause for a period of time
            [nsthread SLEEPFORTIMEINTERVAL:0.002];



2. Number of votes-1
Self.leftticketscount= count-1;

Get current thread
Nsthread *current=[nsthread CurrentThread];
NSLog (@ "%@--sold a ticket, still left%d tickets", current,self.leftticketscount);
}else
{
Exit thread
[Nsthread exit];
}
}
}




-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
{
Open Thread



[Self.thread1 start];
[Self.thread2 start];
[Self.thread3 start];



}



@end



Print results:








Analysis on hidden danger of safety









Third, how to solve

Mutex use format
@synchronized (Lock Object) {//Lock code required}
Note: Lock 1 copies of code with only 1 locks, which are not valid with multiple locks

code example:


code as follows:

//
Yyviewcontroller.m
05-Thread Safety
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//





#import "YYViewController.h"



@interface Yyviewcontroller ()



Number of votes remaining
@property (nonatomic,assign) int leftticketscount;
@property (Nonatomic,strong) Nsthread *thread1;
@property (Nonatomic,strong) Nsthread *thread2;
@property (Nonatomic,strong) Nsthread *thread3;
@end



@implementation Yyviewcontroller



-(void) viewdidload
{
[Super Viewdidload];
By default there are 20 tickets
self.leftticketscount=10;
Open multiple threads, simulate ticket booking



Self.thread1=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];



self.thread1.name=@ "Conductor a";



Self.thread2=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];



self.thread2.name=@ "Conductor B";



Self.thread3=[[nsthread alloc]initwithtarget:self selector: @selector (selltickets) Object:nil];



self.thread3.name=@ "Conductor C";
}




-(void) selltickets
{
while (1) {
@synchronized (self) {//can only add one lock
1. Check the number of votes first



int count=self.leftticketscount;
if (count>0) {
Suspend for some time
[Nsthread sleepfortimeinterval:0.002];
2. Number of votes-1



Self.leftticketscount= count-1;
Get current thread
Nsthread *current=[nsthread CurrentThread];
NSLog (@ "%@--sold a ticket, still left%d tickets", current,self.leftticketscount);



}else
{
Exit thread
[Nsthread exit];
}
}
}
}




-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
{



Open Thread
[Self.thread1 start];
[Self.thread2 start];
[Self.thread3 start];
}



@end



Execution Effect Chart








Advantages and disadvantages of mutual exclusion locks
Advantages: It can effectively prevent the data security problem caused by multithread grabbing resources
Disadvantage: Need to consume a lot of CPU resources

The use of mutexes: Multiple threads rob the same piece of resources
Related jargon: Thread synchronization, multiple threads performing tasks sequentially
Mutex, which is the use of thread synchronization technology

Four: Atomic and non-atomic properties

OC has nonatomic and atomic two choices when defining attributes
Atomic: Atomic properties, lock for setter methods (default is Atomic)
Nonatomic: Non-atomic property, no lock for setter method

Atomic principle of adding locks


 code as follows:

@property (assign, atomic) int age;


-(void) Setage: (int) Age
{

@synchronized (self) {
_age = age;
}
}


Selection of atomic and non-atomic properties
Comparison of Nonatomic and atomic




    • Atomic: Thread-safe, requires a lot of resources to consume
    • Nonatomic: Non-thread safe, suitable for small memory mobile devices


Recommendations for iOS development


    • All attributes are declared as Nonatomic
    • Try to avoid multithreading to rob the same piece of resources
    • As far as possible, lock, resource-grabbing business logic to server-side processing, reduce the pressure of mobile clients
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.