2014-10-19 72 views
3

由於我需要將應用程序從C移植到Swift,我想知道是否有任何關於在Swift上使用pthread_create和pthread_join的示例。我知道通常我們必須使用NSThreads或GCD,但在這種情況下,我需要保持應用程序代碼儘可能接近C應用程序。 任何人都可以在這裏舉個例子嗎? 順便說一下,要調用的函數是一個Swift函數,而不是C函數pthread_create swift sample

回答

1

也面臨這個問題。下面是簡短的示例。希望它可以幫助別人進一步:

斯威夫特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) 
+0

凡pthread_attr_t和東西剩下的聲明?我必須創建一個橋文件嗎? – 2018-02-15 13:30:10

+0

@HolaSoyEduFelizNavidad你不需要做任何橋接的東西。只需進口基金會 - 即'足夠 – 2018-02-15 13:32:41

+0

它可能是新的。當我問這個問題的時候是什麼時候發佈了Swift 1。那時我認爲這些功能是不可用的。我很高興現在有可能做到這一點。 – 2018-02-16 20:57:38