Concurrent vs serial queues in GCD

Posted on 03 Kasım 2018 in Programlama by

There is a good conversation here

An example to running sync call and async queue. Sync task in a different queue blocks current caller thread.
You have two guys – Bob and Mark. Bob makes dough and gives it to Mark to put in the oven. And here you can have two scenarios, either Bob will wait with making next batch of dough until Mark puts current batch in the oven (this would be sync) or he will start right away and won’t bother if Mark did his job already (async)
It may sound like sync does not make sense – what’s the point of concurrency if you have to wait for other thread to finish its work? But actually it has some valid applications. As you know, all UI calls need to be performed on main thread. Let’s assume you have some code which runs in background queue and from time to time it needs to check if app is in the background or foreground. It can be done by asking UIApplication for applicationState, yet calling it from background thread might cause crash or at least a threading warning. So the solution is:

let applicationState = DispatchQueue.main.sync { return UIApplication.shared.applicationState }

This will block current queue until main queue returns this value. You can’t use async here as you need this value to continue your work. Analogy for Bob and Mark would be waiting for Mark to tell Bob if there is still space in the oven for next batch of cake, so Bob can decide if he should make it or not 😉

Please give us your valuable comment

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image

This site uses Akismet to reduce spam. Learn how your comment data is processed.