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;
21 @end
24 @implementation YYViewController
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 }
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 }
74 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
75 {
76 //开启线程
77
78 [self.thread1 start];
79 [self.thread2 start];
80 [self.thread3 start];
82 }
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 {
6 @synchronized(self) {
7 _age = age;
8 }
9 }
原子和非原子属性的选择
nonatomic和atomic对比
atomic:线程安全,需要消耗大量的资源
nonatomic:非线程安全,适合内存小的移动设备
iOS开发的建议
所有属性都声明为nonatomic
尽量避免多线程抢夺同一块资源
尽量将加锁、资源抢夺的业务逻辑交给服务器端处理,减小移动客户端的压力
iOS多线程编程之创建线程安全(转载)的更多相关文章
- iOS多线程编程之创建线程(转载)
一.创建和启动线程简单说明 一个NSThread对象就代表一条线程 (1)创建.启动线程 NSThread *thread = [[NSThread alloc] initWithTarget:sel ...
- java多线程编程(二创建线程)
1.概念 因为java是完全面向对象的,所以在java中,我们说的线程,就是Thread类的一个实例对象.所以,一个线程就是一个对象,它有自己字段和方法. 2.创建线程 创建线程有 ...
- iOS多线程编程原理及实践
摘要:iOS开发中,开发者不仅要做好iOS的内存管理,而且如果你的iOS涉及多线程,那你也必须了解iOS编程中对多线程的限制,iOS主线程的堆栈大小为1M,其它线程均为512KB,且这个限制开发者是无 ...
- iOS多线程编程指南
iOS多线程编程指南(拓展篇)(1) 一.Cocoa 在Cocoa上面使用多线程的指南包括以下这些: (1)不可改变的对象一般是线程安全的.一旦你创建了它们,你可以把这些对象在线程间安全的传递.另一方 ...
- iOS多线程编程之线程的状态(转载)
一.简单介绍 线程的创建: self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil]; ...
- iOS多线程编程指南(二)线程管理
当应用程序生成一个新的线程的时候,该线程变成应用程序进程空间内的一个实体.每个线程都拥有它自己的执行堆栈,由内核调度独立的运行时间片.一个线程可以和其他线程或其他进程通信,执行I/O操作,甚至执行任何 ...
- iOS多线程编程之多线程简单介绍(转载)
一.进程和线程 1.什么是进程 进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开QQ.Xcode,系统就会分别启动2个进程 通过“ ...
- iOS多线程编程之NSThread的使用(转载)
1.简介: 1.1 iOS有三种多线程编程的技术,分别是: 1.NSThread 2.Cocoa NSOperation (iOS多线程编程之NSOperation和NSOperationQueue的 ...
- IOS高级编程之三:IOS 多线程编程
多线程的概念在各个操作系统上都会接触到,windows.Linux.mac os等等这些常用的操作系统,都支持多线程的概念. 当然ios中也不例外,但是线程的运行节点可能是我们平常不太注意的. 例如: ...
随机推荐
- ios开发之--仿(微信)自定义表情键盘
先附上demo:https://github.com/hgl753951/CusEmoji.git 效果图如下:
- luasocket 接收数据
在游戏客户端使用luasocket作为网络通信的手段, 有一点很蛋疼, 就是它的receive是阻塞的, 那界面就卡死在那里了, 不过有一个函数:settimeout(), 传入参数0, 表示如果 ...
- iOS 播放gif动态图的方式探讨
原文链接:http://my.oschina.net/u/2340880/blog/608560 摘要iOS中没有现成的接口来展示gif动态图,但可以通过其他的方式来处理gif图的展示.iOS中播放g ...
- zabbix添加Tomcat监控
参靠了网上一些关于zabbix添加Tomcat的监控配置,自己整理了下: 一.服务器端配置1.找到zabbix源码存放路径 # find / -name zabbix_java #/usr/local ...
- mybatis 之resultType="HashMap" parameterType="list"
<!-- 查询商品仓库信息 --> <select id="loadGoodsStock" resultType="HashMap" para ...
- linux C 调用shell程序执行
#include<stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h ...
- android linphone中opengl显示的实现
1,java层 在界面中创建GL2JNIView(基类为GLSurfaceView). 创建对象AndroidVideoWindowImpl,将GL2JNIView作为参数传入构造函数.在该对象中监听 ...
- TNS-12532: TNS:invalid argument,Oracle的报错信息太让人无语
TNS-12532: TNS:invalid argument,Oracle的报错信息太让人无语 现象: Tnsping报错: [oracle@unicomGZ01 admin]$ ../../bin ...
- css笔记 - animation学习笔记(二)
animation动画 @keyframes规则 - 创建动画 from - to 等价于 0% - 100% 但是优先使用0% - 100%,因为浏览器兼容性还好点 animation 动画绑定 将 ...
- html2canvas - 解决办法之图片跨域导致的截图空白
1. 后端支持:图片要是cdn上的地址,并且允许图片跨域,header头中设置应为 Access-Control-Allow-Origin: * 2. 前端配置 var opts = { scale ...