如何在Swift中设置实时线程?

How to set realtime thread in Swift?

我正在尝试从 Swift 中的 OSX scheduling guide 实现 set_realtime() 函数。

我卡在 thread_policy_set() 上了。以下原因导致此编译器错误:

"Cannot specialize a non-generic definition"

我也尝试了一些其他的东西,但是 &policy 出现了各种类型不匹配错误。任何建议将不胜感激!谢谢!

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() 将指针转换为不同的类型。你必须 "rebind" 指针 相反:

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