아래의 runloop 내 보조 NSThread * processThread NSThread를 공개하는 것이 언제 안전합니까?
호출 스레드를 닫으려면
다음 호출 할 안전합니다 :
[processCondition release];
[processThread release];
또는 필요합니까 스레드가 완료되었는지 확인하려면?
아마 이것처럼?
NSTimeInterval timeout = [NSDate timeIntervalSinceReferenceDate] + (1.0/15.0);
while ([processThread isExecuting] && [NSDate timeIntervalSinceReferenceDate] < timeout)
{
[NSThread sleepForTimeInterval: 1.0/1000.0 ];
}
[processCondition release];
[processThread release];
상세한 코드 명 :
- (void)processLoop
{
NSAutoreleasePool * outerPool = [[NSAutoreleasePool alloc] init];
[processCondition lock];
//outer loop
//this loop runs until my application exits
while (![[NSThread currentThread] isCancelled])
{
NSAutoreleasePool *middlePool = [[NSAutoreleasePool alloc];
if(processGo)
{
//inner loop
//this loop runs typically for a few seconds
while (processGo && ![[NSThread currentThread] isCancelled])
{
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc]; init];
//within inner loop
//this takes a fraction of a second
[self doSomething];
[innerPool release];
}
[self tidyThingsUp];
}
else
{
[processCondition wait];
}
[middlePool release];
}
[processCondition unlock];
[outerPool release];
}
의 조합 :
- 내부 while 루프
- NSCondition * processCondition
- 토글
YES
와NO
사이의processGo
을 사용하면 스레드를 취소하지 않고 내부 while 루프를 중지하고 시작할 수 있습니다.
if (processGo == YES)
실행이 내부 while 루프에 들어갑니다.
processGo = NO
실행시 외부 루프의 다음 패스에서 내부 while 루프와 tidys 를 실행하면
[processCondition wait]
실행이 실행되고 이 대기합니다.
주 스레드가
을 다시 설정하는 경우processGo == YES
및
[processCondition wait]
실행이
로 다시 실행됩니다.
하지 않습니다 쓰레드에서'cancel'을 호출했다고해서 곧바로 해제 할 수 있다고 보장 할 수는 없습니다. – Tim
네,하지만 실행 중에는 그대로 유지됩니다 –
@ 루위 : 네, 맞습니다 - 죄송합니다, didn – Tim