美文网首页iOS 开发 iOS收藏知识
iOS中有关多线程和线程安全的基础知识

iOS中有关多线程和线程安全的基础知识

作者: 黄成 | 来源:发表于2015-07-27 17:03 被阅读2169次

1. 多线程技术

1). NSThread :
1. 使用NSThread对象建立一个线程非常方便;
2. 但是!要使用NSThread管理多个线程非常困难,不推荐使用;
3. 技巧!使用[NSThread currentThread]跟踪任务所在线程,适用于这三种技术.

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadRun) object:nil];
    [thread setName:@"first"];
    [thread start];

2). NSOperation:
1.提供了一些在GCD中不容易实现的特性,如:限制最大并发数量,操作之间的依赖关系.
2.NSOperation有状态返回,能控制其取消等操作,推荐使用多线程的时候用这种方式,灵活


   NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runInvocationOperation) object:nil];
    [invocationOperation setQueuePriority:NSOperationQueuePriorityVeryHigh];
    
    
    NSInvocationOperation *invocationOperation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runInvocationOperation) object:nil];
    [invocationOperation1 setQueuePriority:NSOperationQueuePriorityLow];
    [invocationOperation1 addDependency:invocationOperation];//增加依赖,某个任务完成,才开始这个任务
    [invocationOperation cancel];//取消动作
    [invocationOperation start];//开始动作
    BOOL isExe = invocationOperation.isExecuting;//是否执行中
    BOOL isFinish = invocationOperation.isFinished;//是否结束了
    
    self.queue = [[NSOperationQueue alloc]init];
    [self.queue setMaxConcurrentOperationCount:2];
    [self.queue addOperation:invocationOperation];
    [self.queue addOperation:invocationOperation1];

3). GCD

  1. 操作使用Blocks定义;
  2. 队列负责调度任务执行所在的线程以及具体的执行时间;
  3. 队列的特点是先进先出(FIFO)的,新添加至队列的操作都会排在队尾.
  4. 简单用法:

    dispatch_queue_t serialQueue = dispatch_queue_create("com.cc", nil);//串行分发队列
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//并发分发队列
    
    dispatch_queue_t mainQueue = dispatch_get_main_queue();//主分发队列 主线程
    
    //dispatch_async异步执行
    dispatch_async(mainQueue, ^{
        [NSThread sleepForTimeInterval:5];
    });
     //dispatch_sync阻塞执行
     dispatch_sync(mainQueue, ^{
     [NSThread sleepForTimeInterval:5];
     });//这样会死锁主线程  dispatch_sync等待block执行完,block需要在主线程中运行,相互死锁
    
    //2.gcd group用法
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, concurrentQueue, ^{
        //
    });
    dispatch_group_async(group, concurrentQueue, ^{
        
    });
    dispatch_group_notify(group, mainQueue, ^{
        //group执行完后
    });
  1. 其他用处:
    信号量dispatch semaphore
dispatch_semaphore_create(1);//创建一个初始信号量为1的semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//等待信号量大于0,时间:永远
dispatch_semaphore_signal(semaphore);//释放一个资源,使信号量加1

分发栅栏dispatch barrier

   dispatch_barrier_async(queue, ^{
   });//作用等待queue里面的操作完成后进行block操作

分发源dispatch source

监听指定的各种事件
变量增加dispatch_source_type_data_add
变量OR  dispatch_source_type_data_or
进程相关dispatch_source_type_proc
文件读写
.......

4). 使用performSelecter


    //在当前线程运行
    [self performSelector:@selector(threadRun) withObject:nil afterDelay:1.0];
    //在指定线程运行
    [self performSelector:@selector(threadRun) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES];
    //在后台线程运行
    [self performSelectorInBackground:@selector(threadRun) withObject:nil];
    //在主线程运行
    [self performSelectorOnMainThread:@selector(threadRun) withObject:nil waitUntilDone:YES];

5). 使用pthread创建线程


- (void)launchPthread{
    pthread_attr_t attr;
    pthread_t posixThreadID;
    int returnVal;
    returnVal = pthread_attr_init(&attr);
    assert(!returnVal);
    returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    assert(!returnVal);
    
    int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, NULL);
    returnVal = pthread_attr_destroy(&attr);
    assert(!returnVal);
    if (threadError != 0)
    {
    }
}
void *PosixThreadMainRoutine(void * data){
    NSLog(@"dosomething");
    return NULL;
}

2. 线程数据安全

1). nonatomic atomic
使用atomic多线程原子性控制,atomic的原理给setter加上锁,getter不会加锁


@property (atomic,assign) NSInteger leftTicketsCount;

    //默认有10张票
    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";

    [self.thread1 start];
    [self.thread2 start];
    [self.thread3 start];
-(void)sellTickets
{
    while (true) {
        if (self.leftTicketsCount > 0 ) {
            [NSThread sleepForTimeInterval:0.5];
            self.leftTicketsCount--;
            NSLog(@"thread:%@ ---> %ld",[[NSThread currentThread] name],self.leftTicketsCount);
        }
        else{
            break;
        }
    }
}
输出.png

读取写入并行发生的时候,会出现如上错误

2). 使用GCD实现atomic操作:
给某字段的setter和getter方法加上同步队列:

- (void)setCount:(NSInteger)newcount{
    dispatch_sync(_synQueue, ^{
        count = newcount;
    });
}
- (NSInteger)count{
    __block NSInteger localCount;
    dispatch_sync(_synQueue, ^{
        localCount = count;
    });
    return localCount;
}
gcd添加原子性.png

3). 使用NSLock

_lock = [[NSLock alloc]init];

- (void)threadRunLock{
    while (true) {
        [_lock lock];
        if (self.number > 0 ) {
            [NSThread sleepForTimeInterval:0.5];
            self.number --;
            NSLog(@"thread:%@ ---> %ld",[[NSThread currentThread] name],self.number);
        }
        [_lock unlock];
    }
}

相当于给代码片段加上lock了,所以依次输出9-0

iOS系统提供了三种锁
1.NSLock
2.NSConditionLock;条件锁 --- 条件锁是一个互斥锁,可以通过特定值来锁住和解锁
3.NSRecursiveLock;递归锁 --- 对同一线程,可以多次获得(lock)而不会造成死锁

在unix中,提供POSIX thread lock:
pthread_mutex_t mutex;//互斥锁
pthread_rwlock_t lock;//读写锁
pthread_condattr_t conLock;//条件锁
点击这里查看

4). 使用GCD的信号量和栅栏

在使用一些特殊三方库的时候,例如七牛上传,需要进行异步并发操作,但是七牛自己会有一个下载队列,并且开发者不能获取到这个队列,那么在我们需要设置自己的并发数就会有问题(...)

使用信号量可以很方便的解决该问题:

dispatch_semaphore_create(max);//创建一个初始信号量为max的semaphore

然后在队列添加任务的时候
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//等待信号量大于0,时间:永远
有资源可以使用的时候往下继续
addOpeartion...

在成功或者失败返回的时候
dispatch_semaphore_signal(semaphore);//释放一个资源,使信号量加1

栏栅:

在前面队列执行完成之后执行该操作,简单用法有点像读写锁

总结

目前大概会用到的多线程除了pthread应该都是必须掌握的,线程安全使用原子性(atomic)、NSLock、volatile和信号量比较常用

相关文章

  • IOS多线程安全(线程锁)

    线程安全 线程的不安全是由于多线程访问和修改共享资源而引起的不可预测的结果。ios多线程开发中为保证线程的安全常用...

  • iOS多线程的一些知识点

    讲述一些有关iOS中的多线程知识点,以及一些应用实例 一、多线程基础知识 多线程是一个比较轻量级的方法来实现单个应...

  • OC底层知识(十一) : 多线程

    一、简介:多线程在之前进行过一篇详细的基础博客 iOS多线程 二、多线程的基础知识回顾 1.1、iOS中的常见多线...

  • OC--各种线程锁

    参考:正确使用多线程同步锁@synchronized()iOS中的锁iOS多线程安全详解iOS 常见知识点(三):...

  • 【iOS开发】--多线程(持续更新)

    文章目录: 一: iOS中多线程的实现方案phreadNSThreadGCDNSOpration 二:多线程的安全...

  • 百度iOS面试总结

    原文链接 一面 1、iOS基础知识 2、Python基础知识,大概是多线程,线程安全,集合类,JVM,类相关知识等...

  • iOS多线程到底不安全在哪里?

    iOS多线程到底不安全在哪里? iOS多线程到底不安全在哪里?

  • 百度iOS面试总结

    一面 1、iOS基础知识 2、Python基础知识,大概是多线程,线程安全,集合类,JVM,类相关知识等。 3、i...

  • 轻松学iOS多线程之 GCD 的常用函数

    关于 iOS 多线程中 GCD 的基础知识已在上一篇文章中详细说明,请参看《轻松学iOS多线程之 GCD 的基本使...

  • GeekBand - iOS 多线程和RunLoop 总结

    iOS 开发高级进阶 第三周 多线程 Runloop iOS 多线程以及 RunLoop 学习总结 基础知识 什么...

网友评论

  • ooops:> 2). 使用GCD实现atomic操作:

    这段count是个property?正常property的getter和setter不是这样写的,里面不能直接引用变量本身的
    ooops:@黄成 使用dispatch的串行队列就可以了,相比getter和setter会简单很多 :smile:
    黄成:@ooops 这个是这样的:
    @interface ViewController (){
    NSString *name;
    }

    @property (nonatomic,strong) NSString *name;

    一般用括号外面的比较合适,很多书推荐使用括号里面的,目的是为了防止setting&getting方法误用,但是使用括号里面的 block是访问不到的,而且默认强引用,直接访问是会循环引用。

    我这里是结合起来使用的。

本文标题:iOS中有关多线程和线程安全的基础知识

本文链接:https://www.haomeiwen.com/subject/ylymqttx.html