如何在Swift中设置实时线程? [英] How to set realtime thread in Swift?

查看:145
本文介绍了如何在Swift中设置实时线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此我被困在thread_policy_set()上.以下原因导致此编译器错误:

I'm stuck on thread_policy_set(). The following causes this compiler error:

无法专用于非泛型定义"

"Cannot specialize a non-generic definition"

我也尝试了其他一些方法,但是使用&policy会遇到各种类型的不匹配错误.任何建议将不胜感激!谢谢!

I've also tried a couple other things but get various type mismatch errors with &policy. Any suggestions would be greatly appreciated! Thanks!

func set_realtime(period: UInt32, computation: UInt32, constraint: UInt32) -> Bool {
    let TIME_CONSTRAINT_POLICY: UInt32 = 2
    let TIME_CONSTRAINT_POLICY_COUNT = UInt32(MemoryLayout<thread_time_constraint_policy_data_t>.size / MemoryLayout<integer_t>.size)
    let SUCCESS: Int32 = 0
    var policy: thread_time_constraint_policy
    var ret: Int32
    let thread: thread_port_t = pthread_mach_thread_np(pthread_self())

    policy.period = period
    policy.computation = computation
    policy.constraint = constraint
    policy.preemptible = 1

    ret = withUnsafeMutablePointer<integer_t>(to: &policy, { ptr -> Int32 in
        thread_policy_set(thread, TIME_CONSTRAINT_POLICY, ptr, TIME_CONSTRAINT_POLICY_COUNT)
    })

    if ret != SUCCESS {
        print(stderr, "set_realtime() failed.\n")
        return false
    }
    return true
}

推荐答案

您不能将类型占位符添加到withUnsafeMutablePointer()到 将指针转换为其他类型.您必须重新绑定"指针 相反:

You cannot add a type placeholder to withUnsafeMutablePointer() to cast the pointer to a different type. You have to "rebind" the pointer instead:

ret = withUnsafeMutablePointer(to: &policy) {
    $0.withMemoryRebound(to: integer_t.self, capacity: Int(TIME_CONSTRAINT_POLICY_COUNT)) {
        thread_policy_set(thread, TIME_CONSTRAINT_POLICY, $0, TIME_CONSTRAINT_POLICY_COUNT)
    }
}

这篇关于如何在Swift中设置实时线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆