iOS development multithreaded article-thread safety-top of the text

Source: Internet
Author: User

Original http://www.cnblogs.com/wendingding/p/3805841.html

iOS development multithreaded article-thread safety

One, multi-threaded security risks

Resource sharing

1 of resources may be shared by multiple threads, that is, multiple threads may access the same block of resources

For example, multiple threads access the same object, the same variable, the same file

Data confusion and data security issues can easily arise when multiple threads access the same resource

Example one:

Example two:

Problem code:

 1//2//Yyviewcontroller.m3//05-Thread Safety4//5//Created by Apple on 14-6-23.6//Copyright (c) 2014 itcase. All rights reserved.7//8910#import"YYViewController.h"1112 @Interface Yyviewcontroller ()13//Number of votes left14@property (nonatomic,assign) int leftticketscount;@property (Nonatomic,strong) Nsthread *thread1;@property (Nonatomic,strong) Nsthread *thread2;@property (Nonatomic,strong) Nsthread *thread3;1920@end2223@implementation Yyviewcontroller2526-(void) viewdidload28 {[Super Viewdidload];3031//There are 20 tickets by default3233Self.leftticketscount=10;3435//Open multiple threads and simulate ticket sales3637Self.thread1=[[nsthread Alloc]initwithtarget:Self selector: @selector (selltickets) Object:nil];3839[Email protected]"Conductor a ";4041Self.thread2=[[nsthread Alloc]initwithtarget:Self selector: @selector (selltickets) Object:nil];4243[Email protected]"Conductor B ";4445Self.thread3=[[nsthread Alloc]initwithtarget:Self selector: @selector (selltickets) Object:nil];46[Email protected]"Conductor C ";47}4849-(void) selltickets51 {52while (1) {53//1. Check the number of votes firstcount= intSelf.leftticketscount;55if (count>0) {56//Pause for some time[Nsthread Sleepfortimeinterval:0.002];5859//2. Number of votes-160Self.leftticketscount= count-1;6162//Gets the current threadNsthread *current=[nsthread CurrentThread];NSLog (@"%@--sold a ticket and%d tickets left ", current,Self.leftticketscount);65}Else66 {67 // exit thread 68 [nsthread exit]; }70}71}72 73 74-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) Event75 { 76 // open thread 77 78 [self.thread1 start]; [self.thread2 start]; [self.thread3 start]; Bayi 82}83 84 @end      

Printing results:

Second, the security hidden trouble analysis

Third, how to solve

Mutex use format

@synchronized (Lock Object) {//code to be locked}

Note: Locking 1 parts of code with only 1 locks, with multiple locks is not valid

code example:

 1//2//Yyviewcontroller.m3//05-Thread Safety4//5//Created by Apple on 14-6-23.6//Copyright (c) 2014 itcase. All rights reserved.7//89#import"YYViewController.h"1011 @Interface Yyviewcontroller ()1213//Number of votes left@property (nonatomic,assign) int leftticketscount;@property (Nonatomic,strong) Nsthread *thread1;@property (Nonatomic,strong) Nsthread *thread2;@property (Nonatomic,strong) Nsthread *thread3;@end19@implementation Yyviewcontroller21st-(void) viewdidload23 {[Super Viewdidload];25//There are 20 tickets by default26Self.leftticketscount=10;27//Open multiple threads and simulate ticket sales2829Self.thread1=[[nsthread Alloc]initwithtarget:Self selector: @selector (selltickets) Object:nil];3031[Email protected]"Conductor a ";3233Self.thread2=[[nsthread Alloc]initwithtarget:Self selector: @selector (selltickets) Object:nil];3435[Email protected]"Conductor B ";3637Self.thread3=[[nsthread Alloc]initwithtarget:Self selector: @selector (selltickets) Object:nil];3839[Email protected]"Conductor C ";40}4142-(void) selltickets44 {45while (1) {@synchronized (Self) {//Only one lock can be added.47//1. Check the number of votes first48count= intSelf.leftticketscount;50if (count>0) {51//Pause for some time[Nsthread Sleepfortimeinterval:0.002];53//2. Number of votes-15455Self.leftticketscount= count-1;56//Gets the current threadNsthread *current=[nsthread CurrentThread];NSLog (@"%@--sold a ticket and%d tickets left ", current,Self.leftticketscount);5960}Else61 {62 // exit thread 63 [nsthread exit]; }65}66}67}68 69 70-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event 71 {72 73 //  open thread 74 [self.thread1 start]; [self.thread2 start];self.thread3 start];78 79 @end          

Perform

Advantages and disadvantages of mutual exclusion lock

Advantages: It can effectively prevent the data security problem caused by multi-thread snatch resource

Cons: Consumes a lot of CPU resources

Use of mutexes: Multiple threads rob the same piece of resources

Related jargon: Thread synchronization, multiple threads performing tasks sequentially

Mutex is the use of thread synchronization technology

IV: Atomic and non-atomic properties

OC has nonatomic and atomic two choices when defining attributes

Atomic: Atomic attribute, locking for setter method (default is Atomic)

Nonatomic: Non-atomic attribute, does not lock the setter method

Atomic Plus Lock principle

int age;  3-(void) Setage: (int) Age7 _age = age;  8}9}     

Selection of atomic and non-atomic properties

Comparison of Nonatomic and atomic

Atomic: Thread-safe, requires a lot of resources

Nonatomic: Non-thread-safe, suitable for small memory mobile devices

Recommendations for IOS Development

All properties are declared as Nonatomic

Try to avoid multiple threads robbing the same piece of resources

As far as possible to locking, resource-grabbing business logic to the server-side processing, reduce the pressure of mobile clients

iOS development multithreaded article-thread safety-top of the text

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.