iOS开发多线程篇—线程安全
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开发多线程篇—线程安全的更多相关文章
- iOS开发多线程篇—线程间的通信
iOS开发多线程篇—线程间的通信 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任 ...
- iOS开发多线程篇—线程的状态
iOS开发多线程篇—线程的状态 一.简单介绍 线程的创建: self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(te ...
- iOS开发多线程篇—线程间的通信(转)
这里转载 给自己一个备份 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任务后,转 ...
- iOS开发多线程篇 04 —线程间的通信
iOS开发多线程篇—线程间的通信 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任 ...
- iOS开发多线程篇 03 —线程安全
iOS开发多线程篇—线程安全 一.多线程的安全隐患 资源共享 1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源 比如多个线程访问同一个对象.同一个变量.同一个文件 当多个线程访问同一块 ...
- iOS开发多线程篇—创建线程
iOS开发多线程篇—创建线程 一.创建和启动线程简单说明 一个NSThread对象就代表一条线程 创建.启动线程 (1) NSThread *thread = [[NSThread alloc] in ...
- iOS开发多线程篇—多线程简单介绍
iOS开发多线程篇—多线程简单介绍 一.进程和线程 1.什么是进程 进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开QQ.Xcod ...
- iOS 开发多线程篇—GCD的常见用法
iOS开发多线程篇—GCD的常见用法 一.延迟执行 1.介绍 iOS常见的延时执行有2种方式 (1)调用NSObject的方法 [self performSelector:@selector(run) ...
- iOS开发多线程篇—GCD介绍
iOS开发多线程篇—GCD介绍 一.简单介绍 1.什么是GCD? 全称是Grand Central Dispatch,可译为“牛逼的中枢调度器” 纯C语言,提供了非常多强大的函数 2.GCD的优势 G ...
随机推荐
- JavaScript之旅(DOM)
JavaScript之旅(DOM) [TOC] 一.认识DOM 什么是 DOM? DOM 是 Document Object Model(文档对象模型)的缩写. DOM 是 W3C(万维网联盟)的标准 ...
- javascript时间戳和日期字符串相互转换
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="C ...
- HTML5 Web 客户端五种离线存储方式汇总
最近折腾HTML5游戏需要离线存储功能,便把目前可用的几种HTML5存储方式研究了下,基于HT for Web写了个综合的实例,分别利用了Cookie.WebStorage.IndexedDB以及Fi ...
- QCustomplot使用分享(七) 层(完结)
一.分层绘制 一直说要讲2.0.0版本,但总是想把1.3.2版本拿出来比较一下,这篇文章也不例外.QCustomPlot2.0.0beta版本比1.3.2release版本有一个很大的改进那就是分层绘 ...
- Ionic2学习笔记(1):新建一个页面
作者:Grey 原文地址: http://www.cnblogs.com/greyzeng/p/5532323.html 新建一个页面: 借上一篇中的HelloWorl ...
- C语言写的流氓关机程序及破解
记得大二刚开始接触电脑的那个时候,偶尔会弹出一个强制关机的窗口,当时没有办法,如下: 现在看来只是一个小程序而已,用C语言编写的: #include<windows.h> int main ...
- c#初学-多线程中lock用法的经典实例
本文转载自:http://www.cnblogs.com/promise-7/articles/2354077.html 一.Lock定义 lock 关键字可以用来确保代码块完成运行,而不会被 ...
- jquery可见性选择器(匹配匹配所有显示的元素)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 项目中初试PHP单元测试
只能叫初试,前面虽然做了一些PHPUnit与团队所用框架的整合,但在整个团队还没有人可以主动推动这个事情,而作为Leader最重要的一种能力应该是"让正确的事情发生",所以今天开始 ...
- [moka同学笔记]YII2.0 判断签约状态,sql的两种查询方法
方法一: //判断签约状态 $signed = 0; $sql="SELECT * from usho_community_sign_record WHERE com_id=$r->i ...