简体   繁体   中英

GCD: return on non-main thread

I use dispatch_async in some non-main thread. Let's call it "thread A". I got thread A not by using GCD. After executing some block I want to return in thread A. How can I make it?

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

How about

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

This is kind of an ugly way of doing it, but it seems to work.

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;

Its worth noting that this will block thread A.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM