GCD退出线程执行

来源:互联网 发布:an99软件下载 编辑:程序博客网 时间:2024/06/07 02:11
GCD本身并没有停止正在运行的线程的API,但可以通过添加线程时进行循环判断调用,如果停止的标志为ture则停止线程运行。方法如下:

点击导航栏上的退出则退出线程通讯:
  self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"开始" style:UIBarButtonItemStylePlain target:self action:@selector(testAction)];

- (void)testAction{    NSLog(@"执行了testAction的按钮");    [self closeThread];    [self.navigationController popViewControllerAnimated:YES];}- (void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    q = dispatch_get_global_queue(0, 0);    dispatch_async(q, ^{        while (![self shouldCancel]) {            NSLog(@"query times ");            sleep(2);        };    });}- (void)closeThread{    if (q) {        self.shouldCancel = YES;        dispatch_suspend(q);        dispatch_release(q);        q = nil;    }}


0 0