使用foo_args
,我可以创建一个新线程,我可以与主线程同步或异步运行:
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")
答案 0 :(得分:0)
之前我遇到过类似的问题 - 你可以使用dispatch_semaphore
来暂停和恢复一个帖子。
dispatch_semaphore_wait
递减默认值为0的信号量,您可以指定等待的时间,包括DISPATCH_TIME_FOREVER
和dispatch_semaphore_signal
将其值递增到0然后恢复你的线程。希望有所帮助!
示例(您可以在Playgrounds中尝试此代码):
// 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()