iOS的GCD中如何關閉或者殺死一個還沒執行完的后台線程


思路:設置全局變量flag的值為flase,當取消時,改變flag的值為true,dispatch內部判斷flag,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(@"收到gcd停止信號");

return ;

}

};

});

 

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

NSLog(@"gcd停止信號發出!");

gcdFlag = YES;

});

}

方法二:執行cacel,在selector內部判斷isCancelled,如果是,return或者[NSTread exit];

// cancel:方法僅僅是給線程標記為取消狀態。但是要想真正取消線程的執行,必須在線程內部判斷。 [thread cancel];

方法三:可以改用NSOperationQueue

 

iOS 8 以后,通過dispatch_block_cancel可以cancel掉dispatch_block_t,需要注意的是,未執行的可以用此方法cancel掉,若已經執行則cancel不掉;

如果想中斷(interrupt)線程,可以使用dispatch_block_testcancel方法;

值得注意的是,swift3之后DispatchWorkItem代替了dispatch_block_t,有很方便的cancel()和isCancelled可以使用。

iOS對於多線程的支持有NSThread、NSOperation、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:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM