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

一、多线程的安全隐患

资源共享

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

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

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

示例一:

示例二:

问题代码:

 1 //
2 // YYViewController.m
3 // 05-线程安全
4 //
5 // Created by apple on 14-6-23.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9
10 #import "YYViewController.h"
11
12 @interface YYViewController ()
13 //剩余票数
14
15 @property(nonatomic,assign) int leftTicketsCount;
16 @property(nonatomic,strong)NSThread *thread1;
17 @property(nonatomic,strong)NSThread *thread2;
18 @property(nonatomic,strong)NSThread *thread3;
19
20
21 @end
22
23
24 @implementation YYViewController
25
26
27 - (void)viewDidLoad
28 {
29 [super viewDidLoad];
30
31 //默认有20张票
32
33 self.leftTicketsCount=10;
34
35 //开启多个线程,模拟售票员售票
36
37 self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
38
39 self.thread1.name=@"售票员A";
40
41 self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
42
43 self.thread2.name=@"售票员B";
44
45 self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
46 self.thread3.name=@"售票员C";
47 }
48
49
50 -(void)sellTickets
51 {
52 while (1) {
53 //1.先检查票数
54 int count=self.leftTicketsCount;
55 if (count>0) {
56 //暂停一段时间
57 [NSThread sleepForTimeInterval:0.002];
58
59 //2.票数-1
60 self.leftTicketsCount= count-1;
61
62 //获取当前线程
63 NSThread *current=[NSThread currentThread];
64 NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
65 }else
66 {
67 //退出线程
68 [NSThread exit];
69 }
70 }
71 }
72
73
74 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
75 {
76 //开启线程
77
78 [self.thread1 start];
79 [self.thread2 start];
80 [self.thread3 start];
81
82 }
83
84 @end

打印结果:

二、安全隐患分析

三、如何解决

互斥锁使用格式

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

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

代码示例:

 1 //
2 // YYViewController.m
3 // 05-线程安全
4 //
5 // Created by apple on 14-6-23.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10
11 @interface YYViewController ()
12
13 //剩余票数
14 @property(nonatomic,assign) int leftTicketsCount;
15 @property(nonatomic,strong)NSThread *thread1;
16 @property(nonatomic,strong)NSThread *thread2;
17 @property(nonatomic,strong)NSThread *thread3;
18 @end
19
20 @implementation YYViewController
21
22 - (void)viewDidLoad
23 {
24 [super viewDidLoad];
25 //默认有20张票
26 self.leftTicketsCount=10;
27 //开启多个线程,模拟售票员售票
28
29 self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
30
31 self.thread1.name=@"售票员A";
32
33 self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
34
35 self.thread2.name=@"售票员B";
36
37 self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
38
39 self.thread3.name=@"售票员C";
40 }
41
42
43 -(void)sellTickets
44 {
45 while (1) {
46 @synchronized(self){//只能加一把锁
47 //1.先检查票数
48
49 int count=self.leftTicketsCount;
50 if (count>0) {
51 //暂停一段时间
52 [NSThread sleepForTimeInterval:0.002];
53 //2.票数-1
54
55 self.leftTicketsCount= count-1;
56 //获取当前线程
57 NSThread *current=[NSThread currentThread];
58 NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
59
60 }else
61 {
62 //退出线程
63 [NSThread exit];
64 }
65 }
66 }
67 }
68
69
70 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
71 {
72
73 //开启线程
74 [self.thread1 start];
75 [self.thread2 start];
76 [self.thread3 start];
77 }
78
79 @end

执行效果图

互斥锁的优缺点

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

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

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

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

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

四:原子和非原子属性

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

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

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

atomic加锁原理

1 @property (assign, atomic) int age;
2
3 - (void)setAge:(int)age
4 {
5
6 @synchronized(self) {
7 _age = age;
8 }
9 }

原子和非原子属性的选择

nonatomic和atomic对比

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

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

iOS开发的建议

所有属性都声明为nonatomic

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  9. iOS开发多线程篇—GCD的基本使用

    iOS开发多线程篇—GCD的基本使用 一.主队列介绍 主队列:是和主线程相关联的队列,主队列是GCD自带的一种特殊的串行队列,放在主队列中得任务,都会放到主线程中执行. 提示:如果把任务放到主队列中进 ...

随机推荐

  1. NGINX -- 详解Nginx几种常见实现301重定向方法上的区别

    Nginx下常见的301跳转有以下三种,虽然都能达到同样的目的.但是三种写法上还是有区别的,主要的区别是在正则匹配的性能上. 第一种:使用rewrite指令,通过正则匹配所有的URI后再去掉开头第一个 ...

  2. linux CMakeLists.txt 语法

    CMake入门教程 参考文献:http://www.ibm.com/developerworks/cn/linux/l-cn-cmake/index.html 官方网址:http://www.cmak ...

  3. 本地环境 XAMPP+phpStorm+XDebug+chrome配置和断点调试

    不明白phpStorm+XAMPP+chrome组合的phpStorm配置XDebug的断点调试,很多种网页办法都看过了,可用,但没达预期.QQ群问,一个大牛很奇怪我都配置了怎么还不正确,很干脆地说远 ...

  4. 过滤xss攻击和sql注入函数

    /**+----------------------------------------------------------* The goal of this function is to be a ...

  5. 深度增强学习--DDPG

    DDPG DDPG介绍2 ddpg输出的不是行为的概率, 而是具体的行为, 用于连续动作 (continuous action) 的预测 公式推导 推导 代码实现的gym的pendulum游戏,这个游 ...

  6. HDU 4372 - Count the Buildings(组合计数)

    首先想过n^3的组合方法,即f(i,j,k)=f(i-1,j,k)*(i-2)+f(i-1,j-1,k)+f(i-1,j,k-1),肯定搞不定 然后想了好久没有效果,就去逛大神博客了,结果发现需要用到 ...

  7. Python 操作 ElasticSearch

    Python 操作 ElasticSearch 学习了:https://www.cnblogs.com/shaosks/p/7592229.html 官网:https://elasticsearch- ...

  8. DirectX游戏开发——从一个小游戏開始

    本系列文章由birdlove1987编写,转载请注明出处. 文章链接: http://blog.csdn.net/zhurui_idea/article/details/26364129 写在前面:自 ...

  9. 求x>0时,y=x^3-6x^2+15的极值

    解: 当x→∞时,y也→∞,所以y没有最大值. y=x3-6x2+15=-4*(x/2)*(x/2)*(6-x)+15 而根据几何平均数小于等于算术平均数的定理,(x/2)*(x/2)*(6-x)在x ...

  10. Node.js 向一个文件添加内容

    最简方案: fs.appendFile('message.txt', 'data to append', function (err) { }); 参考文档: http://www.codeweblo ...