带有 ReadabilityHandler 块的 NSTask 竞争条件

Bry*_*yan 2 cocoa objective-c race-condition nstask grand-central-dispatch

基本设置

NSTask用来运行优化图像的过程。此过程将输出数据写入stdout. 我使用的readabilityHandler属性NSTask来捕获该数据。这是缩写的设置:

NSTask *task = [[NSTask alloc] init];
[task setArguments:arguments];  // arguments defined above
                   
NSPipe *errorPipe = [NSPipe pipe];
[task setStandardError:errorPipe];
NSFileHandle *errorFileHandle = [errorPipe fileHandleForReading];
                   
NSPipe *outputPipe = [NSPipe pipe];
[task setStandardOutput:outputPipe];
NSFileHandle *outputFileHandle = [outputPipe fileHandleForReading];
                   
NSMutableData *outputData = [[NSMutableData alloc] init];
NSMutableData *errorOutputData = [[NSMutableData alloc] init];
                   
outputFileHandle.readabilityHandler = ^void(NSFileHandle *handle) { 
      NSLog(@"Appending data for %@", inputPath.lastPathComponent); 
      [outputData appendData:handle.availableData]; 
};

errorFileHandle.readabilityHandler = ^void(NSFileHandle *handle) { 
       [errorOutputData appendData:handle.availableData]; 
};
Run Code Online (Sandbox Code Playgroud)

然后我像这样调用 NSTask:

[task setLaunchPath:_pathToJPEGOptim];
[task launch];
[task waitUntilExit];
Run Code Online (Sandbox Code Playgroud)

(这都是在后台调度队列上完成的)。接下来我检查 NSTask 的返回值:

if ([task terminationStatus] == 0)
{
    newSize = outputData.length;
                           
    if (newSize <= 0)
    {
        NSString *errorString = [[NSString alloc] initWithData:errorOutputData encoding:NSUTF8StringEncoding];
        NSLog(@"ERROR string: %@", errorString);
    }

    // Truncated for brevity...
}
Run Code Online (Sandbox Code Playgroud)

问题

大约 98% 的时间,这都能完美运行。但是,似乎-waitUntilExitCAN 在 readabilityHandler 块运行之前触发。这是一个屏幕截图,显示可读性处理程序在任务退出后正在运行:

在此处输入图片说明

所以这显然是运行 readabilityHandler 的调度队列和我触发 NSTask 的调度队列之间的竞争条件。我的问题是:我到底如何才能确定 readabilityHandler 已完成?如果当 NSTask 告诉我它已经完成时,它可能没有完成,我该如何克服这种竞争条件?


笔记:

我知道 NSTask 有一个可选completionHandler块。但是文档声明此块不能保证在-waitUntilExit返回之前运行,这意味着它甚至可以比-waitUntilExit. 这将使竞争条件更有可能发生。

Bry*_*yan 5

好的,经过多次反复试验,这是处理它的正确方法:

1. 不要使用 -AvailableData

在您的可读性处理程序块中,不要使用该-availableData方法。这有奇怪的副作用,有时不会捕获所有可用数据,并且会干扰系统尝试使用空 NSData 对象调用处理程序以发出管道关闭的信号,因为-availableData在数据实际可用之前会阻塞。

2. 使用 -readDataOfLength:

相反,-readDataOfLength:NSUIntegerMax在您的可读性处理程序块中使用。使用这种方法,处理程序会正确接收一个空的 NSData 对象,您可以使用它来检测管道的关闭并发出信号量信号。

3. 小心 macOS 10.12!

Apple 在 10.13 中修复了一个错误,该错误在这里绝对重要:在旧版本的 macOS 上,如果没有要读取的数据,则永远不会调用可读性处理程序。也就是说,它们永远不会被零长度数据调用以表明它们已完成。这会导致使用信号量方法永久挂起,因为信号量永远不会增加。为了解决这个问题,我测试了 macOS 10.12 或更低版本,如果我在旧操作系统上运行,我使用对 dispatch_semaphore_wait() 的单个调用,并在 NSTask 的 completionHandler 块中对 dispatch_semaphore_signal() 的单个调用配对。我让完成块休眠 0.2 秒以允许处理程序执行。这显然是一个非常丑陋的黑客,但它有效。如果我使用 10.13 plus,我有不同的可读性处理程序来发送信号量(一次来自错误处理程序,一次来自正常输出处理程序),我仍然从 completionHandler 块发送信号量。在我启动任务后,这些与对 dispatch_semaphore_wait() 的 3 次调用配对。在这种情况下,完成块中不需要延迟,因为当 fileHandle 完成时,macOS 会正确调用具有零长度数据的可读性处理程序。


例子:

(注意:假设我的原始问题示例中定义了东西。为了便于阅读,这段代码被缩短了。)

// Create the semaphore
dispatch_semaphore_t sema = dispatch_semaphore_create(0);

// Define a handler to collect output data from our NSTask
outputFileHandle.readabilityHandler = ^void(NSFileHandle *handle)
{
    // DO NOT use -availableData in these handlers.
    NSData *newData = [handle readDataOfLength:NSUIntegerMax];
    if (newData.length == 0) 
    {
        // end of data signal is an empty data object.
        outputFileHandle.readabilityHandler = nil;
        dispatch_semaphore_signal(sema);
    } 
    else 
    {
       [outputData appendData:newData];
    }
};

// Repeat the above for the 'errorFileHandle' readabilityHandler.


[task launch];
  
// two calls to wait because we are going to signal the semaphore once when
// our 'outputFileHandle' pipe closes and once when our 'errorFileHandle' pipe closes                     
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

// ... do stuff when the task is done AND the pipes have finished handling data.

// After doing stuff, release the semaphore
dispatch_release(sema);
sema = NULL;
                   
Run Code Online (Sandbox Code Playgroud)