2017-09-01 31 views
0

使用DispatchQueue,我可以創造一個新的線程,我可以與主線程同步或異步運行:暫停和恢復輔助,同步線程

import Foundation 

let thread = DispatchQueue(label: "thread") 

thread.sync { 
    // Code here... 
} 

我一直在努力做的是運行單獨的線程到某個點,暫停它,繼續運行主線程,然後返回輔助線程。那可能嗎?

這裏有一個例子:

import Foundation 

let thread = DispatchQueue(label: "thread") 

thread.sync { 
    print("Thread Started") 
    // Pause Thread 
    print("Thread Ended") 
} 
print("Before Thread Ended") 
// Start Thread 
print("After Thread Ended") 

所需的輸出:

Thread Started 
Before Thread Ended 
Thread Ended 
After Thread Ended 
+0

你需要某種類型的共享鎖來協調他們。 –

回答

0

我以前也有過類似的問題 - 你可以使用dispatch_semaphore暫停和恢復線程。

dispatch_semaphore_wait遞減具有默認值爲0的信號,你可以指定你想要多少時間就需要等待包括DISPATCH_TIME_FOREVERdispatch_semaphore_signal增加它的值返回到0,然後繼續你的線程。希望有所幫助!

例(你可以嘗試在操場這段代碼):

// Main thread 
let semaphore = DispatchSemaphore(value:0) 
let queue = DispatchQueue(label: "Queue") 

//Asynchronously execute some code on a separate thread 
queue.async { 
    print("Code executed before pause") 

    // This will pause the thread 
    semaphore.wait(timeout: .distantFuture) 

    print("Woohoo - Code executed after resuming the semaphore") 
} 

// Some sort of trigger - I am putting the thread to sleep for 5 sec as next line will otherwise execute straight away  
sleep(5) 

// On main thread resume the semaphore 
semaphore.signal() 
+0

你可以擴展這個,也許有一些示例代碼?之前我曾與之混淆過,但我無法實現它。 –

+0

編輯我的答案 - 見上面的例子。 – Valentin

+0

這幾乎可以工作,但是如果我做了任何需要長時間處理另一個線程(由sleep(1)'模擬)的內容,塊之後的代碼就會在我想要的之前運行。請記住,我希望它以同步方式運行。 –