GCD中的序列化优先级队列

use*_*849 2 multithreading priority-queue grand-central-dispatch

我有来自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 ) ;
     }) ;
}
Run Code Online (Sandbox Code Playgroud)

teg*_*eye 5

我不确定是否有人提供了答案,但是请不要这样做。充其量,您只需在这里为三个队列设置优先级。最糟糕的是,您什么都不做。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);
Run Code Online (Sandbox Code Playgroud)

然后像这样使用每个:

dispatch_async(queueA,highAction);
dispatch_async(queueB,mediumAction);
dispatch_async(queueC,lowAction);
Run Code Online (Sandbox Code Playgroud)