2012-04-27 161 views
1

我有这样的问题:NSOperationQueue VS并行线程的优先级

  • 我有一些使用线程的C++代码。这些线程是pthread类型。我使用NSOperationQueue和一些C++代码。

问题是这样的:C++ pthread的优先级总是低于NsOperationQueue

我该如何解决这个问题?我也试图给NSOpertionQueue低优先级,但此修复程序不起作用。

回答

1

如果你不得不求助于优先级(特别是向上),它通常表示并发模型的设计缺陷。这应该保留用于非常特殊的情况,例如实时线程(例如音频回放)。

首先评估您的线程和任务如何操作,并确保您没有其他选择。通常情况下,您可以做一些简单的事情,例如减少操作队列的最大操作数,减少总线程数,或将您的任务按其需要的资源分组。

你用什么方法来确定线程的优先级?

另请注意,设置操作的优先级会影响排队操作的排序(而不是线程本身)。

我一直可以通过调整分配来解决这个问题。你应该现在停止阅读:)


可用,但不建议:

为了降低操作的优先级,你可以在接近它的操作的main

- (void)main 
{ 
    @autorelease { 
    const double priority = [NSThread threadPriority]; 
    const bool isMainThread = [NSThread isMainThread]; 
    if (!isMainThread) { 
     [NSThread setThreadPriority:priority * 0.5]; 
    } 

    do_your_work_here 

    if (!isMainThread) { 
     [NSThread setThreadPriority:priority]; 
    } 
    } 
} 

如果您毕竟真的需要推内核,这是你如何设置pthread的优先级:

pthreads with real time priority

How to increase thread priority in pthreads?