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

思路:設置全局變量flag的值爲flase,當取消時,改變flag的值爲true,dispatch內部判斷flag,return;swift

 

BOOL gcdFlag = NO;多線程

 

- (void)viewDidLoad {app

[super viewDidLoad];async

dispatch_async(dispatch_get_global_queue(0, 0), ^{ui

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

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

sleep(1);code

 

if (gcdFlag==YES) {orm

NSLog(@"收到gcd中止信號");rem

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:

相關文章
相關標籤/搜索