Pthread_create quick selection
Due to the fact that I need to port my application from C to Swift, I would like to know if there is any sample about using pthread_create and pthread_join in Swift. I know that usually we should use NSThreads or GCD, but in this case, I want the application code to be as close as possible to the C application. Can you set an example here? By the way, the called function is a Swift function, not a C function
+3
source to share
1 answer
Faced a problem. Below is a short example. Hope this helps someone else:
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)
+1
source to share