【问题标题】:How to set thread priority of a coroutine dispatcher in Kotlin Native如何在 Kotlin Native 中设置协程调度程序的线程优先级
【发布时间】:2021-04-20 11:53:10
【问题描述】:

我在我的多平台(Android + iOS)应用程序中使用协程。为了能够使用多线程协同程序,我使用native-mt 构建。所以现在我需要创建一个在高优先级线程上运行的CoroutineDispatcher。在android上我是这样做的

val thread = HandlerThread("myThread", -20).also {
    it.start()
}
val highPriorityDispatcher = Handler(thread.looper).asCoroutineDispatcher()

有没有办法在 iOS 上创建类似的高优先级调度程序?

首先我尝试使用newSingleThreadContext 创建一个新的调度程序。在 k/n 中,生成的调度程序公开了它的Worker,但我还没有找到任何设置工作优先级的方法。 我还尝试使用setThreadPriority 方法提高线程优先级:

val highPriorityDispatcher = newSingleThreadContext("myThread").also {
    scope.launch(it){
        NSThread.setThreadPriority(1.0)
    }
}

但似乎没有起到应有的作用。

我正在考虑使用dispatch_queue 编写自定义调度程序,但这似乎是一项不平凡的任务。因此,如果您能找到更简单的方法来解决这个问题,我们将不胜感激。

【问题讨论】:

    标签: kotlin kotlin-coroutines kotlin-native


    【解决方案1】:

    好吧,其实我好像错了。

    val highPriorityDispatcher = newSingleThreadContext("myThread").also {
        scope.launch(it){
            NSThread.setThreadPriority(1.0)
        }
    }
    

    完成这项工作并实际更改优先级,在 iOS 分析器中确认。 最后我也加了

      pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0)
    

    调用来设置 QoS。我使用了pthread 版本,因为here 是这么说的

    NSThread 拥有一个 qualityOfService 属性,类型为 NSQualityOfService。此类不会根据 其执行的上下文,所以这个属性的值可能只是 在线程开始之前更改。阅读 qualityOfService 的 线程随时提供其当前值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      相关资源
      最近更新 更多