何时释放NSThread是否安全?

com*_*eye 4 iphone multithreading objective-c

下面是我的辅助NSThread*processThread的runloop

关闭我打电话的主题

//cancel secondary thread
[processThread cancel]
//signal condition
[processCondition broadcast];
Run Code Online (Sandbox Code Playgroud)

然后可以安全地打电话:

[processCondition release];
[processThread release];
Run Code Online (Sandbox Code Playgroud)

或者我需要确定线程已完成?

也许是这样的?

NSTimeInterval timeout = [NSDate timeIntervalSinceReferenceDate] + (1.0/15.0);

while ([processThread isExecuting] && [NSDate timeIntervalSinceReferenceDate] < timeout)
{
    [NSThread sleepForTimeInterval: 1.0/1000.0 ];
}

[processCondition release];
[processThread release];
Run Code Online (Sandbox Code Playgroud)




详细代码和说明:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

组合:

  • 一个内在的循环
  • NSCondition*processCondition
  • processGoYES和之间切换NO

允许我停止并启动内部while循环而不取消线程.

if (processGo == YES)
Run Code Online (Sandbox Code Playgroud)


执行进入内部while循环.

当主线程设置时

processGo = NO
Run Code Online (Sandbox Code Playgroud)

执行离开内部while循环并
在外循环的下一次传递中整理,执行命中

[processCondition wait]
Run Code Online (Sandbox Code Playgroud)

并等待

如果主线程重置

processGo == YES
Run Code Online (Sandbox Code Playgroud)

和电话

[processCondition wait]
Run Code Online (Sandbox Code Playgroud)

执行重新进入内循环

Lou*_*arg 8

是的,如果您已完成NSThread,则可以安全地调用NSThread.在非GC Objective C代码中,习惯用法是,一旦您完成对象的访问,您就可以释放它.如果还有其他东西需要该对象,包括对象本身,那么他们的工作就是保留它.通常,如果物体在任意时间不能安全地处置,它将在其处于不安全状态时保持自身,并且当它可以被安全地处理时释放它自己.

这就是NSThread和NSURLConnection之类的工作方式(NSURLConnection实际上保留了它的委托,并做了许多花哨的东西来应对发生的保留循环.