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 ...
随机推荐
- Windows Azure Cloud Service (44) 将Cloud Service加入Virtual Network Subnet,并固定Virtual IP Address(VIP)
<Windows Azure Platform 系列文章目录> 在之前的文章中,笔者已经详细介绍了如何将Virtual Machine加入Virtual Network,并且绑定固定的Pr ...
- JS&CSS文件请求合并及压缩处理研究(四)
本篇将会尝试对之前的代码进行相关的单元测试,验证路径合并规则的覆盖率及正确性. 熟悉 ASP.NET MVC 开发的朋友应该知道,微软在MVC框架下集成了一款名为 Microsoft.VisualSt ...
- JAVA 设计模式 迭代器模式
用途 迭代器模式 (Iterator) 提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示. 迭代器模式是一种行为型模式. 结构
- 解决SpringMVC的@ResponseBody返回中文乱码
SpringMVC的@ResponseBody返回中文乱码的原因是SpringMVC默认处理的字符集是ISO-8859-1,在Spring的org.springframework.http.conve ...
- JS魔法堂:再次认识Function.prototype.call
一.前言 大家先预计一下以下四个函数调用的结果吧! var test = function(){ console.log('hello w ...
- 解决VS Code调试.NET Core应用遇到的坑
为什么会有”坑“ 博客园里有好多介绍怎么使用VS Code以及调试.NET Core的文章,但是都是基于直接构建Asp.Net Core Mvc单项目的,有什么区别呢! (1).我们这次遇到的坑是在多 ...
- python生成随机密码
有时候我们会想生成一个随机密码,这样我们通过Python中的一些随机方法,就可生成我们任意长度和复杂度的密码,代码如下: # -*- coding=utf-8 -*- import random im ...
- [转]virtualenv建立多个Python独立开发环境
不同的人喜欢用不同的方式建立各自的开发环境,但在几乎所有的编程社区,总有一个(或一个以上)开发环境让人更容易接受. 使用不同的开发环境虽然没有什么错误,但有些环境设置更容易进行便利的测试,并做一些重复 ...
- WinForm对话框
WinForm 对话框控件colorDialog - 颜色选择对话框 使用代码如下: private void 字体颜色ToolStripMenuItem_Click(object sender, E ...
- ExtJs动态生成treepanel的Json格式
在节点中加上"checked"属性,会自动生成checkbox. 获取选中节点 var nodeArray = ""; var nodesObj = mytre ...