pthread_create swift样本

时间:2014-10-19 11:28:12

标签: swift pthreads

由于我需要将应用程序从C移植到Swift,我想知道是否有关于在Swift上使用pthread_create和pthread_join的示例。我知道通常我们必须使用NSThreads或GCD,但在这种情况下,我需要保持应用程序代码尽可能接近C应用程序。 谁能在这里举个例子? 顺便说一句,要调用的函数是Swift函数,而不是C函数

1 个答案:

答案 0 :(得分:2)

也面临这个问题。这是下面的简短示例。希望它能进一步帮助别人:

Swift 4

class ThreadContext {

    var someValue: String = "Some value"
}

func doSomething(pointer: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {

    let pContext = pointer.bindMemory(to: ThreadContext.self, capacity: 1)
    print("Hello world: \(pContext.pointee.someValue)")

    return nil
}

var attibutes = UnsafeMutablePointer<pthread_attr_t>.allocate(capacity: 1)
guard 0 == pthread_attr_init(attibutes) else {

    fatalError("unable to initialize attributes")
}

defer {

    pthread_attr_destroy(attibutes)
}

guard 0 == pthread_attr_setdetachstate(attibutes, PTHREAD_CREATE_JOINABLE) else {

    fatalError("unable to set detach state")
}

let pContext = UnsafeMutablePointer<ThreadContext>.allocate(capacity: 1)
var context = ThreadContext()
pContext.pointee = context

var thread: pthread_t? = nil
let result = pthread_create(&thread, attibutes, doSomething, pContext)

guard result == 0, let thread = thread else {

    fatalError("unable to start pthread")
}

pthread_join(thread, nil)