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);

扫描二维码关注公众号,回复: 96237 查看本文章

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:

猜你喜欢

转载自www.cnblogs.com/dengchaojie/p/8976952.html
今日推荐