您的位置:首页 > 其它

GCD退出线程执行

2015-10-07 13:25 411 查看
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;
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: