1

dispatch_async在一些非主线程中使用。我们称它为“线程 A”。我不是通过使用 GCD 得到线程 A。执行完某个块后,我想在线程 A 中返回。我该怎么做?

胎面A:

dispatch_queue_t fetchQ = dispatch_queue_create("Thread B", NULL);
dispatch_async(fetchQ, ^{
    // Do some stuff...
    // ...

    //Now I want to return in Thread A
});
dispatch_release(fetchQ);
4

2 回答 2

0

这是一种丑陋的做法,但它似乎有效。

dispatch_queue_t fetchQ = dispatch_queue_create("Thread B", NULL);

__block BOOL changeWhenComplete = NO;

dispatch_async(fetchQ, ^{

    for (int i =0; i < 2; i++) {

        NSLog(@"doing work");
        sleep(1);
    }
    //Now I want to return in Thread A
    changeWhenComplete = YES;
});
dispatch_release(fetchQ);

while (!changeWhenComplete) {

    sleep(1);
    NSLog(@"waiting for fetchQ to complete");
}

NSLog(@"fetchQ returned");
return;

值得注意的是,这将阻塞线程 A。

于 2013-07-11T07:32:22.220 回答
0

怎么样

dispatch_queue_t fetchA = ...
//..

dispatch_queue_t fetchQ = dispatch_queue_create("Thread B", NULL);
dispatch_async(fetchQ, ^{
    // Do some stuff...
    // ...

    dispatch_async(fetchA, ^{
        // Do stuff on Tread A
    });

});
dispatch_release(fetchQ);
于 2013-07-11T07:23:07.813 回答