浅析iOS应用开发中线程间的通信与线程安全问题

 更新时间:2015年11月18日 09:27:35   作者:文顶顶  
这篇文章主要介绍了浅析iOS应用开发中线程间的通信与线程安全问题,谈到了包括互斥锁的使用等设计要点,需要的朋友可以参考下

线程间的通信
 
简单说明
线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信
 
线程间通信的体现
1个线程传递数据给另1个线程
在1个线程中执行完特定任务后,转到另1个线程继续执行任务
 
线程间通信常用方法

复制代码 代码如下:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

线程间通信示例 – 图片下载

2015111892145343.png (600×346)

复制代码 代码如下:

//
//  YYViewController.m
//  06-NSThread04-线程间通信
//
//  Created by apple on 14-6-23.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYViewController.h"
@interface YYViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@end


复制代码 代码如下:

@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

// 在子线程中调用download方法下载图片
    [self performSelectorInBackground:@selector(download) withObject:nil];
}

 

-(void)download
{
    //1.根据URL下载图片
    //从网络中下载图片
    NSURL *urlstr=[NSURL URLWithString:@"fdsf"];

    //把图片转换为二进制的数据
    NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时

    //把数据转换成图片
    UIImage *image=[UIImage imageWithData:data];
 
    //2.回到主线程中设置图片
    [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
}

 

//设置显示图片
-(void)settingImage:(UIImage *)image
{
    self.iconView.image=image;
}

@end


代码2:
复制代码 代码如下:

//
//  YYViewController.m
//  06-NSThread04-线程间通信
//
//  Created by apple on 14-6-23.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYViewController.h"
#import <NSData.h>

@interface YYViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@end


复制代码 代码如下:

@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

 
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 在子线程中调用download方法下载图片

    [self performSelectorInBackground:@selector(download) withObject:nil];
}

 
-(void)download
{

    //1.根据URL下载图片
    //从网络中下载图片
    NSURL *urlstr=[NSURL URLWithString:@"fdsf"];

    //把图片转换为二进制的数据
    NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时

    //把数据转换成图片
    UIImage *image=[UIImage imageWithData:data];

    //2.回到主线程中设置图片
    //第一种方式
//    [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];

    //第二种方式
    //    [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];

    //第三种方式
   [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
}


//设置显示图片
//-(void)settingImage:(UIImage *)image
//{
//    self.iconView.image=image;
//}

@end

线程安全
 
一、多线程的安全隐患
资源共享
1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源
比如多个线程访问同一个对象、同一个变量、同一个文件
当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
示例一:

2015111892251282.png (664×387)

示例二:

2015111892312267.png (659×386)

问题代码:

复制代码 代码如下:

//
//  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=10;

    //开启多个线程,模拟售票员售票

    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) {
        //1.先检查票数
        int count=self.leftTicketsCount;
        if (count>0) {
            //暂停一段时间
            [NSThread sleepForTimeInterval:0.002];

            //2.票数-1
           self.leftTicketsCount= count-1;
 
            //获取当前线程
            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


打印结果:

2015111892340617.png (871×448)

二、安全隐患分析

2015111892405061.png (625×320)

2015111892430149.png (678×379)

三、如何解决
 
互斥锁使用格式
@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=10;
    //开启多个线程,模拟售票员售票

    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) {
        @synchronized(self){//只能加一把锁
        //1.先检查票数

        int count=self.leftTicketsCount;
        if (count>0) {
            //暂停一段时间
            [NSThread sleepForTimeInterval:0.002];
            //2.票数-1

           self.leftTicketsCount= count-1;
            //获取当前线程
            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


执行效果图

2015111892457124.png (876×191)

互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的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开发中使用writeToFile时的注意事项

    IOS开发中使用writeToFile时的注意事项

    本篇文章主要介绍了开发中使用writeToFile时的注意事项,具有很好的参考价值。下面跟着小编一起来看下吧
    2017-03-03
  • iOS视频录制(或选择)压缩及上传功能(整理)

    iOS视频录制(或选择)压缩及上传功能(整理)

    最新做的一个功能涉及到了视频的录制、压缩及上传功能,经过大神的一番教导,终于倒腾清楚了,今天小编把问题经过记录一下分享到脚本之家平台,供大家参考
    2017-03-03
  • iOS 中使用tableView实现右滑显示选择功能

    iOS 中使用tableView实现右滑显示选择功能

    这篇文章主要介绍了iOS 中使用tableView实现右滑显示选择功能的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-07-07
  • 个人对于异步和多线程的关系的理解分享

    个人对于异步和多线程的关系的理解分享

    异步和多线程并不是一个同等关系,异步是最终目的,多线程只是我们实现异步的一种手段。异步是当一个调用请求发送给被调用者,而调用者不用等待其结果的返回而可以做其它的事情。
    2014-08-08
  • iOS CoreData 增删改查详解

    iOS CoreData 增删改查详解

    这篇文章主要为大家详细介绍了iOS CoreData 增删改查的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • iOS13 适配和Xcode11.0踩坑小结

    iOS13 适配和Xcode11.0踩坑小结

    这篇文章主要介绍了iOS13 适配和Xcode11.0踩坑小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • iOS实现多个垂直滑动条并列视图

    iOS实现多个垂直滑动条并列视图

    这篇文章主要为大家详细介绍了iOS实现多个垂直滑动条并列视图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • iOS中使用UIDatePicker制作时间选择器的实例教程

    iOS中使用UIDatePicker制作时间选择器的实例教程

    这篇文章主要介绍了iOS中使用UIDatePicker制作时间选择器的实例教程,实例中未选中的时间项目会讲解一个将其变透明的方法,非常给力,需要的朋友可以参考下
    2016-05-05
  • iOS实现代码只执行一次

    iOS实现代码只执行一次

    本文给大家分享的是在iOS中控制代码在整个软件生命周期中只运行一次的代码,有需要的小伙伴可以参考下。
    2016-03-03
  • iOS开发技巧之WeakSelf宏的进化详解

    iOS开发技巧之WeakSelf宏的进化详解

    在程序中我们经常用到Block,但写weak self 时会比较繁琐,下面这篇文章主要给大家介绍了关于iOS开发技巧之WeakSelf宏的进化的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们一起来看看吧
    2018-05-05

最新评论