How to close or kill an unfinished background thread in GCD of iOS

Idea: Set the value of the global variable flag to flase, when canceled, change the value of flag to true, and dispatch internally to judge the flag and return;

 

BOOL gcdFlag = NO;

 

- (void)viewDidLoad {

[super viewDidLoad];

dispatch_async(dispatch_get_global_queue(0, 0), ^{

for (long i=0; i<100000; i++) {

NSLog(@"i:%ld",i);

sleep(1);

 

if (gcdFlag==YES) {

NSLog(@"Receive gcd stop signal");

return ;

}

};

});

 

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

NSLog(@"gcd stops signaling!");

gcdFlag = YES;

});

}

Method 2: Execute cacel, judge isCancelled inside the selector, if so, return or [NSTread exit];

// cancel: The method just marks the thread as canceled. But in order to really cancel the execution of the thread, it must be judged within the thread. [thread cancel];

Method 3: You can use it instead NSOperationQueue.

 

After iOS 8, dispatch_block_t can be canceled through dispatch_block_cancel . It should be noted that this method can be used to cancel if it has not been executed. If it has been executed, it will not be canceled;

If you want to interrupt the thread, you can use the dispatch_block_testcancel method;

It is worth noting that after swift3, DispatchWorkItem replaced dispatch_block_t, and there are very convenient cancel() and isCancelled that can be used.

iOS supports multithreading with NSThread, NSOperation, and GCD.
 

NSCondition

semantics follow those used for POSIX-style conditions.

A condition object acts as both a lock and a checkpoint in a given thread. The lock protects your code while it tests the condition and performs the task triggered by the condition. The checkpoint behavior requires that the condition be true before the thread proceeds with its task. While the condition is not true, the thread blocks. It remains blocked until another thread signals the condition object. 

The semantics for using an NSCondition object are as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212297&siteId=291194637