【问题标题】:NSOperationQueue vs pthread priorityNSOperationQueue 与 pthread 优先级
【发布时间】:2012-04-27 09:23:03
【问题描述】:

我有这个问题:

  • 我有一个使用一些线程的 C++ 代码。这些线程是 pthread 类型的。
  • 在我的 iPhone 应用程序中,我使用 NSOperationQueue 以及一些 C++ 代码。

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

我该如何解决这个问题?我也尝试将NSOpertionQueue 设为低优先级,但此修复不起作用。

【问题讨论】:

    标签: c++ objective-c pthreads nsoperationqueue thread-priority


    【解决方案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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多