iOS NSCondition详解

 iOS  NSCondition讲解

1.定义

官方文档:The NSCondition class implements a condition variable whose semantics follow those used for POSIX-style conditions. A condition object acts as both a lock and a checkpoint in a given thread. The lock protects your code while it tests the condition and performs the task triggered by the condition. The checkpoint behavior requires that the condition be true before the thread proceeds with its task. While the condition is not true, the thread blocks. It remains blocked until another thread signals the condition object.

NSCondition 的对象实际上作为一个锁和一个线程检查器:锁主要为了当检测条件时保护数据源,执行条件引发的任务;线程检查器主要是根据条件决定是否继续运行线程,即线程是否被阻塞。

2.使用

NSConditon *condition =[ [NSCondition alloc]]init;

[condition lock];//一般用于多线程同时访问、修改同一个数据源,保证在同一时间内数据源只被访问、修改一次,其他线程的命令需要在lock 外等待,只到unlock ,才可访问

[condition unlock];//与lock 同时使用

[condition wait];//让当前线程处于等待状态

[condition signal];//CPU发信号告诉线程不用在等待,可以继续执行

3.代码学习:

代码分析:condition 进入到判断条件中,当products == 0 的时候,condition 调用wait 时当前线程处于等待状态;其他线程开始访问products,当NSObject 创建完成并加入到products时,cpu发出single的信号时,处于等待的线程被唤醒,开始执行[products removeObjectAtIndex:0];


3.使用场景:

目前我主要使用于图片消息:

当接受到图片消息的时候,需要异步下载,等到图片下载完成之后,同步数据库,方可通知前端更新UI。此时就需要使用NSCondition 的wait 

//伪代码

- (void)receiveMessage:(MessageEntity *)message

{

NSCondition *condition = [[NSCondition alloc]init];

[condition lock];

NSInteger imageCount ;

void(^unlock)=^(){

while(!imageCount)

[condition signal];

}

imageCount++;

dowanloadImageFinished:^(UIImage *image){ //异步下载图片,下载完成的回调中

imageCount--;

unlock();

}

while(imageCount){

[condition wait];

}

[condition unLock];

}

鉴于商业保密,点到为止,即时通讯IM如需帮助,QQ:983202699。

推荐阅读更多精彩内容