【问题标题】:Serialized priority queues in GCDGCD 中的序列化优先级队列
【发布时间】:2014-05-24 17:49:36
【问题描述】:

我有一段来自 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 ) ;
     }) ;
}

【问题讨论】:

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


    【解决方案1】:

    我不确定是否有人已经为您提供了答案,但请不要这样做。充其量,您只需在此处为三个队列设置优先级。在最坏的情况下,你什么也没做。 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);
    

    然后使用每个like:

    dispatch_async(queueA,highAction);
    dispatch_async(queueB,mediumAction);
    dispatch_async(queueC,lowAction);
    

    【讨论】:

    • 请注意,在 iOS8 中引入了 dispatch_queue_attr_make_with_qos_class 和为 dispatch_queue_create 指定队列优先级的能力。对于早期的 iO​​S 版本,使用 dispatch_set_target_queue() 如下所述:stackoverflow.com/a/17690878/962153
    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 2011-12-20
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    相关资源
    最近更新 更多