pthread_create swift sample

Due to I need to port an application from C to Swift I would like to know if there is any sample about using pthread_create, and pthread_join on Swift. I know that usually we have to use NSThreads or the GCD but in this case I need to keep the application code the closest possible to the C application. Can anyone put an example here? By the way, the function to be called is a Swift function, not a C function

Upvotes: 4

Views: 2046

Answers (1)

Igor B.
Igor B.

Reputation: 2229

Faced the problem too. Here is short sample below. Hope it help someone further:

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)

Upvotes: 4

Related Questions