Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a DispatchSemaphore to control a thread on main queue?

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.

like image 414
aneuryzm Avatar asked Aug 28 '19 13:08

aneuryzm


1 Answers

All of this in on the main thread, so the semaphore.signal() will never be called because the thread will stop on the semaphore.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.

like image 87
dktaylor Avatar answered Oct 14 '22 18:10

dktaylor