Apparently I can only use DispatchSemaphore if I deal with different queues. But what if I want to run async code on the same queue (in this case the main queue).
let s = DispatchSemaphore(value : 0)
DispatchQueue.main.async {
s.signal()
}
s.wait()
This snippet doesn't work, because the async code is also waiting, because the semaphore blocked the main queue. Can I do this with semaphore? Or do I need to run the async code on a different queue?
ps. I know I could use sync, instead of async and semaphore in this snippet. But This is just an example code to reproduce an async call.
All of this in on the main thread, so the
semaphore.signal()
will never be called because the thread will stop on thesemaphore.wait()
and not continue on.If you are trying to run some async code and have the main thread wait for it, run that code on a different queue and have it signal the semaphore when it's done, allowing the main thread to continue.