How to safely use [NSTask waitUntilExit] on the main thread?

I have a multi-threaded program that must run several executable files at once and wait for their results.

I use [nstask waitUntilExit]in NSOperationQueue, which runs it on a non-main thread (starting NSTaskin the main thread is completely out of the question).

My program randomly crashes or works with assertion errors, and crash stacks always point to runloop run by waitUntilExit, which performs various callbacks and handlers, including - IMHO incorrectly - KVO and bindings that update the user interface , which causes them to start by not the main thread (this is possibly the problem described by Mike Ash )

How can I use it safely waitUntilExit?

Is the problem waitUntilExitnot applicable, or do I need to do something special (besides explicitly scheduling my callbacks in the main thread) when using the KVO and IB bindings so that they are not handled incorrectly by thread running waitUntilExit?

+4
source share
2 answers

As Mike Ash points out, you just can't call waitUntilExitrandom runloop. It is convenient, but it does not work. You must include “not working” when calculating “is it really convenient?”

terminationHandler 10.7+. runloop, . waitUntilExit - (, , ):

dispatch_group group = dispatch_group_create();
dispatch_group_enter(group);
task.terminationHandler = ^{ dispatch_group_leave(group); };
[task launch];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

// If not using ARC:
dispatch_release(group);
+4

, ...

. , KVO NSTasks , .

-[NSObject performSelectorOnMainThread:];

, .

:

  • NSOperationQueue maxConcurentOperationsCount = 1 ( FIFO) NSOperation, NSTask . , . ( ).

  • , , . , 2 : NSTask , root .

, .

0

Source: https://habr.com/ru/post/1625862/


All Articles