iOS NSCondition详解

作者: 久林的技术随笔 | 来源:发表于2015-11-01 21:49 被阅读5863次

 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。

相关文章

  • iOS NSCondition详解

    iOS NSCondition讲解 1.定义 官方文档:The NSCondition class impleme...

  • iOS同步锁小探

    我测试的iOS同步锁包括@synchronsized、NSLock、NSCondition、NSCondition...

  • 线程锁

    探讨iOS开发中各种锁使用NSCondition实现多线程同步 NSCondition是线程同步, 阻塞线程。 取...

  • Lock

    iOS中以NS开头常见的锁的有NSCondition、NSConditionLock、NSLock、NSRecur...

  • iOS锁-NSCondition

    NSCondition 下面是苹果官方文档的说法: A condition variable whose sema...

  • iOS Runtime

    iOS RunLoop详解---重要而详细iOS RunLoop详解-部分

  • iOS 修饰词 详解

    iOS 修饰词 详解 iOS 修饰词 详解

  • iOS 简约加载动画详解

    iOS 简约加载动画详解 iOS 简约加载动画详解

  • iOS AFNetWorking源码详解(一)

    原文地址: iOS AFNetWorking源码详解(一) iOS AFNetWorking源码详解(二) iOS...

  • iOS 题目详解 部分一

    主要记录一些题目所关联的知识点, 详解 iOS 题目详解 部分一iOS 题目详解 部分二iOS 题目详解 部...

网友评论

本文标题:iOS NSCondition详解

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