我正在從一個應用程序接收來自HTTP連接的數據,並且數據由一個或多個線程進行處理。我使用NSCondition來允許讀者線程等待傳入數據,並且擁有連接線程在數據可用時廣播它們,但是我一直處於死鎖狀態,我看不出爲什麼。我要麼誤解NSCondition是如何工作的,要麼我長期以來一直盯着它看,我錯過了其他的東西。下面的代碼:NSCondition死鎖
// lock = NSCondition ivar
// position = long long ivar
// writeDataToFile performs no locking but just writes the data to an NSHandle and logs in debug
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[condition lock];
@try {
[self writeDataToFile:data];
position += [data length];
hasMoreData = YES;
} @finally {
[condition broadcast];
[condition unlock];
}
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
int statusCode = [httpResponse statusCode];
requestSuccess = (statusCode == 200);
[condition lock];
[condition broadcast];
[condition unlock];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
[condition lock];
hasMoreData = YES;
[condition broadcast];
[condition unlock];
}
- (void)waitForData {
[condition lock];
@try {
while(!hasMoreData) {
[condition wait];
}
} @finally {
hasMoreData = NO;
[condition unlock];
}
}
現在這一般工作,但偶爾我看到應用程序掛起和樣品展示一個線程等待條件,另一個等待waitForData
獲得鎖和其他等待獲取鎖`連接:didReceiveData」。
我的理解是,[condition wait]
調用原子地解鎖它的內部互斥並等待條件,因此多個等待線程不應阻止線程獲取和廣播條件。
我錯過了什麼?
謝謝, Ĵ
感謝您的建議,但我解鎖失敗方法中的條件(問題已更新,包括代碼)。我沒有包含它,因爲在這種情況下,由於線程懸掛在連接中,連接不會失敗:didReceiveData:selector。 – JWood