iOS开发多线程篇—线程安全

一、多线程的安全隐患

资源共享

1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源

比如多个线程访问同一个对象、同一个变量、同一个文件

当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题

示例一:

示例二:

问题代码:

 //
// YYViewController.m
// 05-线程安全
//
// Created by apple on 14-6-23.
// Copyright (c) 2014年 itcase. All rights reserved.
// #import "YYViewController.h" @interface YYViewController ()
//剩余票数 @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]; //默认有20张票 self.leftTicketsCount=; //开启多个线程,模拟售票员售票 self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread1.name=@"售票员A"; self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread2.name=@"售票员B"; self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread3.name=@"售票员C";
} -(void)sellTickets
{
while () {
//1.先检查票数
int count=self.leftTicketsCount;
if (count>) {
//暂停一段时间
[NSThread sleepForTimeInterval:0.002]; //2.票数-1
self.leftTicketsCount= count-; //获取当前线程
NSThread *current=[NSThread currentThread];
NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
}else
{
//退出线程
[NSThread exit];
}
}
} -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//开启线程 [self.thread1 start];
[self.thread2 start];
[self.thread3 start]; } @end

打印结果:

二、安全隐患分析

三、如何解决

互斥锁使用格式

@synchronized(锁对象) { // 需要锁定的代码  }

注意:锁定1份代码只用1把锁,用多把锁是无效的

代码示例:

 //
// YYViewController.m
// 05-线程安全
//
// Created by apple on 14-6-23.
// Copyright (c) 2014年 itcase. All rights reserved.
// #import "YYViewController.h" @interface YYViewController () //剩余票数
@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];
//默认有20张票
self.leftTicketsCount=;
//开启多个线程,模拟售票员售票 self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread1.name=@"售票员A"; self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread2.name=@"售票员B"; self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread3.name=@"售票员C";
} -(void)sellTickets
{
while () {
@synchronized(self){//只能加一把锁
//1.先检查票数 int count=self.leftTicketsCount;
if (count>) {
//暂停一段时间
[NSThread sleepForTimeInterval:0.002];
//2.票数-1 self.leftTicketsCount= count-;
//获取当前线程
NSThread *current=[NSThread currentThread];
NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount); }else
{
//退出线程
[NSThread exit];
}
}
}
} -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{ //开启线程
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
} @end

执行效果图

互斥锁的优缺点

优点:能有效防止因多线程抢夺资源造成的数据安全问题

缺点:需要消耗大量的CPU资源

互斥锁的使用前提:多条线程抢夺同一块资源

相关专业术语:线程同步,多条线程按顺序地执行任务

互斥锁,就是使用了线程同步技术

四:原子和非原子属性

OC在定义属性时有nonatomic和atomic两种选择

atomic:原子属性,为setter方法加锁(默认就是atomic)

nonatomic:非原子属性,不会为setter方法加锁

atomic加锁原理

 @property (assign, atomic) int age;

 - (void)setAge:(int)age
{ @synchronized(self) {
_age = age;
}
}

原子和非原子属性的选择

nonatomic和atomic对比

atomic:线程安全,需要消耗大量的资源

nonatomic:非线程安全,适合内存小的移动设备

iOS开发的建议

所有属性都声明为nonatomic

尽量避免多线程抢夺同一块资源

尽量将加锁、资源抢夺的业务逻辑交给服务器端处理,减小移动客户端的压力

iOS开发多线程篇—线程安全的更多相关文章

  1. iOS开发多线程篇—线程间的通信

    iOS开发多线程篇—线程间的通信 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任 ...

  2. iOS开发多线程篇—线程的状态

    iOS开发多线程篇—线程的状态 一.简单介绍 线程的创建: self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(te ...

  3. iOS开发多线程篇—线程间的通信(转)

    这里转载 给自己一个备份 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任务后,转 ...

  4. iOS开发多线程篇 04 —线程间的通信

    iOS开发多线程篇—线程间的通信 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任 ...

  5. iOS开发多线程篇 03 —线程安全

    iOS开发多线程篇—线程安全 一.多线程的安全隐患 资源共享 1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源 比如多个线程访问同一个对象.同一个变量.同一个文件 当多个线程访问同一块 ...

  6. iOS开发多线程篇—创建线程

    iOS开发多线程篇—创建线程 一.创建和启动线程简单说明 一个NSThread对象就代表一条线程 创建.启动线程 (1) NSThread *thread = [[NSThread alloc] in ...

  7. iOS开发多线程篇—多线程简单介绍

    iOS开发多线程篇—多线程简单介绍 一.进程和线程 1.什么是进程 进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开QQ.Xcod ...

  8. iOS 开发多线程篇—GCD的常见用法

    iOS开发多线程篇—GCD的常见用法 一.延迟执行 1.介绍 iOS常见的延时执行有2种方式 (1)调用NSObject的方法 [self performSelector:@selector(run) ...

  9. iOS开发多线程篇—GCD介绍

    iOS开发多线程篇—GCD介绍 一.简单介绍 1.什么是GCD? 全称是Grand Central Dispatch,可译为“牛逼的中枢调度器” 纯C语言,提供了非常多强大的函数 2.GCD的优势 G ...

随机推荐

  1. sublime Text3使用笔记

    转载:http://blog.csdn.net/u012771929/article/details/30030249 目录: 1.setting 安装插件,package control ,Emme ...

  2. CSS魔法堂:再次认识font

    一.前言 文字承载着站点内涵,而良好的字体.排版则为用户提供舒适的阅读体验.本文打算对字体稍微深入一下子网页字体的内容,若有纰漏请大家指正,谢谢! 目录一坨: 二, 字体分类 1. 衬线体(Serif ...

  3. noip 模拟赛 匹配 //贪婪策略

    匹配(match.pas/match.c/match.cpp) [题目描述] 到了新的学期,Mcx痛苦的发现通用技术课居然是有实验课的,这样的话他就不得不放弃写作业的想法而去做一件类似于搭积木的事情. ...

  4. SQLServer存储过程中事务的使用

    create proc usp_Stock @GoodsId int, @Number int, @StockPrice money, @SupplierId int, @EmpId int, ), ...

  5. 从C#到Objective-C,循序渐进学习苹果开发(3)--分类(category)和协议Protocal的理解

    本随笔系列主要介绍从一个Windows平台从事C#开发到Mac平台苹果开发的一系列感想和体验历程,本系列文章是在起步阶段逐步积累的,希望带给大家更好,更真实的转换历程体验.本文继续上一篇随笔<从 ...

  6. ASP.Net中防止页面刷新重复提交的几种方法

    [摘要] 目前很多网站都要提交页面插入或更新数据库,比如留言本,一个用户提交留言后,如果按F5,就会重新提交一遍留言,导致数据库出现两条一模一样的留言,本文介绍了几种防止页面刷新,导致重复提交数据的方 ...

  7. [水煮 ASP.NET Web API2 方法论](3-8)怎样给指定路由配置处理器

    阅读导航 问题 解决方案 工作原理 代码演示 问题 如果仅仅针对指定的路由进行某些特定的消息处理,而不是应用于所有路由,我们应该怎么做呢? 解决方案 ASP.NET WEB API 的很多功能都内建了 ...

  8. asp.net中Ajax控件的用途(一)

    1,UpdatePanel控件,用户更新部分内容,示例 放入一个Label和一个Button,单击按钮,label显示当前时间. 2,ScriptManagerProxy控件,每个页面只能有一个Scr ...

  9. 第 19 章 CSS 其他样式

    学习要点: 1.颜色和透明度 2.盒子阴影和轮廓 3.光标样式 主讲教师:李炎恢 本章主要探讨 HTML5 中 CSS 其他剩下几个常用的样式,包括颜色.透明度.盒子的阴影轮廓以及光标的样式. 一.颜 ...

  10. No.013:Roman to Integer

    问题: Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from ...