pthread_create 快速示例 [英] pthread_create swift sample
问题描述
由于我需要将应用程序从 C 移植到 Swift,我想知道是否有任何关于在 Swift 上使用 pthread_create 和 pthread_join 的示例.我知道通常我们必须使用 NSThreads 或 GCD,但在这种情况下,我需要使应用程序代码尽可能接近 C 应用程序.任何人都可以在这里举个例子吗?顺便说一下,要调用的函数是 Swift 函数,而不是 C 函数
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
推荐答案
也遇到了这个问题.这是下面的简短示例.希望它能进一步帮助别人:
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)
这篇关于pthread_create 快速示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!