线程通信以及多线程的不安全性

2017-07-03  本文已影响62人  大猿媛

线程通信

在一个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信
线程通信的体现:
1、一个线程需要传递数据给另一个线程
2、一个线程执行完任务后需要到另一个线程中继续执行

线程通信的方式

//一个线程执行完任务后需要到另一个线程中继续执行
dispatch_async(dispatch_get_global_queue(0, 0), ^{   
        //下载图片完成  主线程更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
        });
        
    });
    NSDictionary *dic = @{@"name":@"wss"};
      //隐式创建并启动线程
    [self performSelectorInBackground:@selector(testInvocation:) withObject:dic];
      -(void)testInvocation:(id)object{
            for (int i=0; i<5; i++) {
                 NSLog(@"thread=====%@,====%d",[NSThread currentThread],i);   
                //<NSThread: 0x60800007e5c0>{number = 3, name = (null)},---4
        
         }
   }
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        //下载图片
        UIImage *img = [UIImage imageNamed:@""];
        [self performSelectorOnMainThread:@selector(downLoadFinish:) withObject:img waitUntilDone:NO];
        
  });
  //下载完成  主线程更新UI 
-(void)downLoadFinish:(UIImage*)img{
    
  }
多线程的不安全性

多线程的不安全主要体现在数据的不安全性。多线程能让多个任务并发执行(尽管是假象的并发执行),但是的确存在两个操作会交错执行的情况,这个时候,如果两个操作访问的是同一块内存区域,并且存在写入的情况,那么就会导致数据错乱,或者程序崩溃

   @property(atomic,assign)int intA; //
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 1; i <= 10000; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread A: %d\n", self.intA);
        }
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 1; i <= 10000; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread B: %d\n", self.intA);
        }
    });
@property (atomic, strong) NSString*      stringA;
 
//thread A
 dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 100000; i ++) {
             if (i % 2 == 0) {
                self.stringA = @"a very long string";
             }else {
                self.stringA = @"string";
            }
            NSLog(@"Thread A: %@\n", self.stringA);
       }
}
 
//thread B
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
           for (int i = 0; i < 100000; i ++) {
              if (self.stringA.length >= 10) {
                   NSString* subStr = [self.stringA substringWithRange:NSMakeRange(0, 10)];
               }
             NSLog(@"Thread B: %@\n", self.stringA);
          }
 }
避免线程安全问题

线程隐患在于多线程能够并发执行,那么,当有些操作存在这种安全隐患的时候,避免并发执行,实现同步执行就不会出现错误

//就像两个买票线程,同一个车次的列车在一个线程中处理的时候必须加锁,另一个线程不能同时操作
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.lock lock];
        for (int i = 1; i <= 10000; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread A: %d\n", self.intA);
        }
        [self.lock unlock];
    });    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.lock lock];

        for (int i = 1; i <= 10000; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread B: %d\n", self.intA);
        }
        [self.lock unlock];
    });
dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @synchronized (self) {
            for (int i = 1; i <= 100; i ++) {
                self.intA = self.intA + 1;
                NSLog(@"Thread A: %d\n", self.intA);
            }
        }
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @synchronized (self) {
            for (int i = 1; i <= 100; i ++) {
                self.intA = self.intA + 1;
                NSLog(@"Thread B: %d\n", self.intA);
            }

        }

    });
 //创建全局信号量   viewdidload中
 //创建信号量  值为1
semaphore = dispatch_semaphore_create(1);

     /**
     *  semaphore:等待信号
     DISPATCH_TIME_FOREVER:等待时间
     wait之后信号量-1,为0
     */
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
            for (int i = 1; i <= 100; i ++) {
                self.intA = self.intA + 1;
                NSLog(@"Thread A: %d\n", self.intA);
            }
    });
    
    /**
     *  发送一个信号通知,这时候信号量+1,为1
     */
    dispatch_semaphore_signal(semaphore);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
            for (int i = 1; i <= 100; i ++) {
                self.intA = self.intA + 1;
                NSLog(@"Thread B: %d\n", self.intA);
            }
    });
//线程1 发出wait信号, 线程2 先执行 ,完毕发出通知信号signal,线程1才执行
dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [self.condition lock];
        [self.condition wait];

        for (int i = 1; i <= 100; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread A: %d\n", self.intA);
         
        }
        [self.condition unlock];
    });
    
    //先执行
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.condition lock];

        for (int i = 1; i <= 100; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread B: %d\n", self.intA);
    
        }
        [self.condition unlock];
        [self.condition signal];    
    });

也有人说这是个互斥锁
NSConditionLock同样实现了NSLocking协议,试验过程中发现性能很低

   dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.conditionLock lock];

            for (int i = 1; i <= 100; i ++) {
                self.intA = self.intA + 1;
                NSLog(@"Thread A: %d\n", self.intA);
            }
        [self.conditionLock unlock];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.conditionLock lock];

            for (int i = 1; i <= 100; i ++) {
                self.intA = self.intA + 1;
                NSLog(@"Thread B: %d\n", self.intA);
            }
        [self.conditionLock unlock];

    });

NSConditionLock也可以像NSCondition一样做多线程之间的任务等待调用,而且是线程安全的。

  //初始化锁的condition 是 1
    self.conditionLock = [[NSConditionLock alloc]initWithCondition:1];

    //lockWhenCondition 当condition和初始化或者当前condition值一样的时候成功
    //unlockWithCondition  解锁,并赋予condition新的值,不能和解锁前的值一样
    //后执行, self.conditionLock 的condition是1
    dispatch_async(dispatch_get_global_queue(0, 0), ^{   
        [self.conditionLock lockWhenCondition:2];   
        for (int i = 1; i <= 100; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread A: %d\n", self.intA);
        }
        [self.conditionLock unlock];
    });
    
    //先执行
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       //当前self.conditionLock 的 condition是1 ,所以lockWhenCondition成功
        [self.conditionLock lockWhenCondition:1];
        for (int i = 1; i <= 100; i ++) {
            self.intA = self.intA + 1;
            NSLog(@"Thread B: %d\n", self.intA);
        } 
      //unlockWithCondition:2  以保证让线程A 执行
        [self.conditionLock unlockWithCondition:2];  
    });
- (void)getIamgeName:(NSMutableArray *)imageNames{
    NSString *imageName;
    [self.recursiveLock lock];
    if (imageNames.count>0) {
        imageName = [imageNames firstObject];
        [imageNames removeObjectAtIndex:0];
        [self getIamgeName:imageNames];
    }
    [self.recursiveLock unlock];
}

dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self getIamgeName:imgsArr];
    });

- (void)dealloc{
    pthread_mutex_destroy(&mutex);  //释放该锁的数据结构
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    pthread_mutex_init(&mutex, NULL);
    /**
     *  初始化
     *
     */
}

- (void)getIamgeName:(NSMutableArray *)imageNames{
    NSString *imageName;
    /**
     *  加锁
     */
    pthread_mutex_lock(&mutex);
    if (imageNames.count>0) {
        imageName = [imageNames firstObject];
        [imageNames removeObjectAtIndex:0];
    }
    /**
     *  解锁
     */
    pthread_mutex_unlock(&mutex);
}

POSIX还可以创建条件锁,提供了和NSCondition一样的条件控制,初始化互斥锁同时使用pthread_cond_init来初始化条件数据结构

// 初始化
    int pthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *attr);

    // 等待(会阻塞)
    int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mut);

    // 定时等待
    int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mut, const struct timespec *abstime);

    // 唤醒
    int pthread_cond_signal (pthread_cond_t *cond);

    // 广播唤醒
    int pthread_cond_broadcast (pthread_cond_t *cond);

    // 销毁
    int pthread_cond_destroy (pthread_cond_t *cond);

POSIX还提供了很多函数,有一套完整的API,包含Pthreads线程的创建控制等等,非常底层,可以手动处理线程的各个状态的转换即管理生命周期,甚至可以实现一套自己的多线程,感兴趣的可以继续深入了解。推荐一篇详细文章,但不是基于iOS的,是基于Linux的,但是介绍的非常详细 Linux 线程锁详解

上一篇下一篇

猜你喜欢

热点阅读