【发布时间】: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