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; ui
[condition lock];//通常用於多線程同時訪問、修改同一個數據源,保證在同一時間內數據源只被訪問、修改一次,其餘線程的命令須要在lock 外等待,只到unlock ,纔可訪問 線程
[condition unlock];//與lock 同時使用 code
[condition wait];//讓當前線程處於等待狀態 orm
[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];
}