简体   繁体   English

2个后台进程的队列

[英]Queue of 2 background processes

I need to create queue of 2 background processes that will work synchronously. 我需要创建2个后台进程的队列,这些队列将同步工作。

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...");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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