简体   繁体   中英

Queue of 2 background processes

I need to create queue of 2 background processes that will work synchronously.

I trying with this code but not get it. Where is my mistake?

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  //block1
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    //block2
  });
});

If I understand your question, you need to create a serial queue if you want your blocks to run synchronously:

dispatch_queue_t queue = dispatch_queue_create("queue-name", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
  // first block
});
dispatch_async(queue, ^{
  // second block
});

Both these blocks will run on some unnamed background thread, but they will run synchronously. The first block will finish executing before the second block begins.

You probably don't want to use the background priority. This queue will run backed by the default priority global queue, which is almost certainly what you want.

You can write code in single thread with sync that will run synchronously one after other.

dispatch_queue_t queue = dispatch_queue_create("queue-name", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
    // first block
    for (int i = 0; i < 100; i++)
    {
        NSLog(@"value = %d",i);
        sleep(1);
    }
       NSLog(@"Hi...");
});

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