GCD中的序列化优先级队列

时间:2014-05-24 17:49:36

标签: multithreading grand-central-dispatch priority-queue

我有一段来自API黑暗时代的现有代码。这是一个基于MPCreateTask的线程。看起来我可以将它移动到GCG队列,但有一点复杂。目前有三个基于MPCreateQueue的队列用于三个优先级。

在GCD中我已经找到了,并测试了下面的代码作为GCD重构的概念证明(天哪,我讨厌这个词,但它适合)。

首先,这是否会按照我的预期进行,即所有操作(对例程的输入块)都是串行的。操作将具有例程指定的优先级。

第二,有更好的方法吗?

// set up three serial queues
dispatch_queue_t queueA = dispatch_queue_create("app.queue.A" , DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queueB = dispatch_queue_create("app.queue.B" , DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queueC = dispatch_queue_create("app.queue.C" , DISPATCH_QUEUE_SERIAL);

// set the target queues so that all blocks posted to any of the queues are serial
// ( the priority of the queues will be set by queueC.
dispatch_set_target_queue( queueB, queueC ) ;
dispatch_set_target_queue( queueA, queueB ) ;

void lowPriorityDispatch( dispatch_block_t lowAction )
{
     dispatch_async( queueC, ^{
        lowAction() ;
     }) ;
}
void mediumPriorityDispatch( dispatch_block_t mediumAction )
{
     dispatch_async( queueB, ^{
        dispatch_suspend( queueC) ;
        mediumAction() ;
        dispatch_resume( queueC ) ;
     }) ;
}
void highPriorityDispatch( dispatch_block_t highAction )
{
     dispatch_async( queueA, ^{
        dispatch_suspend( queueC) ;
        dispatch_suspend( queueB) ;
        highAction() ;
        dispatch_resume( queueB ) ;
        dispatch_resume( queueC ) ;
     }) ;
}

1 个答案:

答案 0 :(得分:4)

我不确定是否有人为您提供了答案,但不要这样做。充其量,您只需在此设置三个队列的优先级。在最坏的情况下,你没有做任何事情。 GCD具有为每个队列创建优先级的工具。请参阅dispatch_queue_attr_make_with_qos_class dispatch_queue_attr_make_with_qos_class

更好的解决方案是:

dispatch_queue_attr_t highPriorityAttr = dispatch_queue_attr_make_with_qos_class (DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED,-1);
dispatch_queue_t queueA = dispatch_queue_create ("app.queue.A",highPriorityAttr);

dispatch_queue_attr_t mediumPriorityAttr = dispatch_queue_attr_make_with_qos_class (DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY,-1);
dispatch_queue_t queueB = dispatch_queue_create ("app.queue.B",mediumPriorityAttr);

dispatch_queue_attr_t lowPriorityAttr = dispatch_queue_attr_make_with_qos_class (DISPATCH_QUEUE_SERIAL, QOS_CLASS_BACKGROUND,-1);
dispatch_queue_t queueC = dispatch_queue_create ("app.queue.C",lowPriorityAttr);

然后使用每个:

dispatch_async(queueA,highAction);
dispatch_async(queueB,mediumAction);
dispatch_async(queueC,lowAction);
相关问题