简体   繁体   English

如何在 Kotlin Native 中设置协程调度程序的线程优先级

[英]How to set thread priority of a coroutine dispatcher in Kotlin Native

I'm using coroutines in my multiplatform (android + iOS) application.我在我的多平台(android + iOS)应用程序中使用协程。 To be able to use multithreaded coroutines, I'm using native-mt builds.为了能够使用多线程协同程序,我使用的是native-mt构建。 So now I need to create a CoroutineDispatcher which runs on a hight priority thread.所以现在我需要创建一个在高优先级线程上运行的CoroutineDispatcher On android I'm doing it like this在 android 我这样做

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

Is there a way to create a similar hight-priority dispatcher on iOS?有没有办法在 iOS 上创建类似的高优先级调度程序?

First what I tried is to create a new dispatcher using newSingleThreadContext .首先,我尝试使用newSingleThreadContext创建一个新的调度程序。 In k/n the resulting dispatcher exposes its Worker , but I have not found any ways to set worker priority.在 k/n 中,生成的调度程序公开了它的Worker ,但我还没有找到任何设置工作者优先级的方法。 Also I tried to raise thread priority with the setThreadPriority method:我还尝试使用setThreadPriority方法提高线程优先级:

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

But it did not seem to have the proper effect.但它似乎没有产生应有的效果。

I'm thinking about writing a custom dispatcher using dispatch_queue , but it seems to be a non-trivial task.我正在考虑使用dispatch_queue编写自定义调度程序,但这似乎是一项不平凡的任务。 So any help to find an easier way to solve this problem would be appreciated.因此,我们将不胜感激找到更简单的方法来解决此问题的任何帮助。

Ok, actually it seems I was wrong.好吧,其实我好像错了。

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

does the job and actually changes the priority, confirmed in the iOS profiler.完成工作并实际更改优先级,在 iOS 分析器中确认。 At the end I also added最后我还添加了

  pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0)

call to set the QoS.调用来设置 QoS。 I used the pthread version, because here it says that我使用了pthread版本,因为这里

NSThread possesses a qualityOfService property, of type NSQualityOfService. NSThread 拥有一个 NSQualityOfService 类型的 qualityOfService 属性。 This class will not infer a QoS based on the context of its execution, so the value of this property may only be changed before the thread has started.此 class 不会根据其执行上下文推断 QoS,因此此属性的值只能在线程启动之前更改。 Reading the qualityOfService of a thread at any time provides its current value.随时读取线程的 qualityOfService 可提供其当前值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM