2017-09-01 15 views
0

は、私はメインスレッドと同期または非同期で実行することができ、新しいスレッド、作成することができます。私がやろうとしてきた何一時停止と二、同期スレッドを再起動

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") 

所望の出力: - あなたがスレッドを一時停止し、再開するdispatch_semaphoreを使用することができます

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

あなたが共有ロックのいくつかの種類とそれらを調整する必要があります。 –

答えて

0

前に、私は同様の問題を持っていた。ここ

は例示です。

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)でシミュレートした、他のスレッドの内部に長い時間がかかる場合は、ブロックが実行される前にコードが実行されます。覚えておいて、私はこれを同期的に実行します。 –

関連する問題