zoukankan      html  css  js  c++  java
  • 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:

  • 相关阅读:
    几种常见的Map的区别
    BlockingQueue详解
    Android开发过程中内存泄露检测
    Android studio 技巧设置(持续更新中)
    Android Support兼容包详解
    单例模式的饿汉式为什么需要双重锁定
    View分析
    Activity的启动流程分析
    LeetCode第十四题-字符串数组中最长的共同前缀
    LeetCode第十三题-将罗马数字转化为数字
  • 原文地址:https://www.cnblogs.com/dengchaojie/p/8976952.html
Copyright © 2011-2022 走看看