1

I would like to execute some sequential jobs in a iOS application. I want to ensure that a job is not executed until the previous one has finished. Firstly a tried to do something like this

group = dispatch_group_create();
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_async(group, queue, ^{
// Job 1
// ...
});
dispatch_group_async(group, queue, ^{
// Job 2
// ...
});

On this way, sometimes the job 2 start executing when the job 1 is still executing.

Then I though of using this way:

group = dispatch_group_create();
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_notify(group, queue, ^{
// Job 1
// ...
});
dispatch_group_notify(group, queue, ^{
// Job 2
// ...
});

The behavior is the same, because the job 1 hasn't been asynchronously dispatched, so the dispatch_group_notify() function thinks there's nothing executing and the job 2 is dispatched without waiting to the job 1.

I found another solution:

group = dispatch_group_create();
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_notify(group, queue, ^{
    dispatch_group_async(group, queue, ^{
    // Job 1
    // ...
    });
});
dispatch_group_notify(group, queue, ^{
    dispatch_group_async(group, queue, ^{
    // Job 2
    // ...
    });
});

Now everything works fine.

Do you find any problem with this dispatch-inside-dispatch structure? Or is it fine?

Thank you!

4

2 回答 2

2

它比你做的更容易,只需使用串行队列:

dispatch_queue_t myQueue ;
myQueue = dispatch_queue_create("cua.prova", nil);

dispatch_async(myQueue, ^{
    NSLog(@"Job 1");
});

dispatch_async(myQueue, ^{
    NSLog(@"Job 2");
});

dispatch_async(myQueue, ^{
    NSLog(@"Job 3");
});

Job 1 总是在 Job 2 之前执行,Job 3 在 Job 2 之后执行,但它们都不在主线程中

于 2013-10-28T22:57:46.647 回答
2

你得到的全局队列

queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

是一个并发队列。如果您希望您的作业按顺序执行,只需创建一个串行队列

queue = dispatch_queue_create("com.company.myqueue", NULL);
于 2013-06-05T12:00:47.303 回答