Unfortunately, for all the benefits provided by dispatch queues, they’re not a panacea for all performance issues. There are three well-known problems that you can run into when implementing concurrency in your app if you’re not careful:
Race conditions
Deadlock
Priority inversion
Race conditions
Threads that share the same process, which also includes your app itself, share the same address space. What this means is that each thread is trying to read and write to the same shared resource. If you aren’t careful, you can run into race conditions in which multiple threads are trying to write to the same variable at the same time.
Consider the example where you have two threads executing, and they’re both trying to update your object’s count variable. Reads and writes are separate tasks that the computer cannot execute as a single operation. Computers work on clock cycles in which each tick of the clock allows a single operation to execute.
Note: Do not confuse a computer’s clock cycle with the clock on your watch. An iPhone XS has a 2.49 GHz processor, meaning it can perform 2,490,000,000 clock cycles per second!
Thread 1 and thread 2 both want to update the count, and so you write some nice clean code like so:
count += 1
Seems pretty innocuous, right? Break that statement down into its component parts, add a bit of hand-waving, and what you end up with is something like this:
Load value of variable count into memory.
Increment value of count by one in memory.
Write newly updated count back to disk.
The above graphic shows:
Thread 1 kicked off a clock cycle before thread 2 and read the value 1 from count.
On the second clock cycle, thread 1 updates the in-memory value to 2 and thread 2 reads the value 1 from count.
On the third clock cycle, thread 1 now writes the value 2 back to the count variable. However, thread 2 is just now updating the in-memory value from 1 to 2.
On the fourth clock cycle, thread 2 now also writes the value 2 to count… except you expected to see the value 3 because two separate threads both updated the value.
This type of race condition leads to incredibly complicated debugging due to the non-deterministic nature of these scenarios.
If thread 1 had started just two clock cycles earlier you’d have the value 3 as expected, but don’t forget how many of these clock cycles happen per second.
You might run the program 20 times and get the correct result, then deploy it and start getting bug reports.
You can usually solve race conditions with a serial queue, as long as you know they are happening. If your program has a variable that needs to be accessed concurrently, you can wrap the reads and writes with a private queue, like this:
private let threadSafeCountQueue = DispatchQueue(label: "...")
private var _count = 0
public var count: Int {
get {
return threadSafeCountQueue.sync {
_count
}
}
set {
threadSafeCountQueue.sync {
_count = newValue
}
}
}
Because you’ve not stated otherwise, the threadSafeCountQueue is a serial queue.
Remember, that means that only a single operation can start at a time. You’re thus controlling the access to the variable and ensuring that only a single thread at a time can access the variable. If you’re doing a simple read/write like the above, this is the best solution.
Note: You can implement the same private queue sync for lazy variables, which might be run against multiple threads. If you don’t, you could end up with two instances of the lazy variable initializer being run. Much like the variable assignment from before, the two threads could attempt to access the same lazy variable at nearly identical times. Once the second thread tries to access the lazy variable, it wasn’t initialized yet, but it is about to be created by the access of the first thread. A classic race condition.
Thread barrier
Sometimes, your shared resource requires more complex logic in its getters and setters than a simple variable modification. You’ll frequently see questions related to this online, and often they come with solutions related to locks and semaphores. Locking is very hard to implement properly. Instead, you can use Apple’s dispatch barrier solution from GCD.
Oq fei mjoutu a jujkusvikm wueia, gie xiz sfovocw ib peyj zuoq srbu derbx og xaa devh ev nqiv gug owy kay aw xva zeso qapa.
Ccex zni lozuaqdo soaws ya ya zyerrog zu, swoz hae neog ci gicd rabc zte kieoa bi mpiq esazcmfizb awfiovm pafralyuy fekjsejoz, rom fu tup tornuhtoifh uxi jol eydud xnu ehkoru paxnxozaz.
Jue oqrzopesx o burdokjx ralsiof izbhiizq skif yev:
Imagine you’re driving down a two-lane road on a bright sunny day and you arrive at your destination. Your destination is on the other side of the road, so you turn on the car’s turn signal. You wait as tons of traffic drives in the other direction.
Njase suoliqx, karu temp loqe em suhifk coi. Zoa vtuh qezedi e toc goqely cve iqres gum pomq iqy munl xamfub eh evm ir iyqi jsith u job raty xovh puo, xeb eq im viy kzozjib dv daol rayvex.
Erviqfodohiry, ykara ofi daxe buft jopobh dne ospozund nuv uyl mi nmo avjoh yani zahmc ar al jafm, rmaqriwz heuk akofugb wu rarz ewhe heud guqjiciraij aft bxooj lfo cahe.
Toe’go vip huunviv roeyxojb, ag yuo epu jeff diufecx ez egavvov nebp lhib lev bohuz vogxfucu. Diektuq uk loo waw hukf ud wurk uru phofpimc dje eqdlaksus fu suac seycaditaoxq.
Kuohsurj ac a zwahxn gamo apgedvakde ic Pgokw bxibdixhuqr, ibmeys fea odi odiyx colilyods pisa dufifjuxoq en udvog efkwapas rumgobj guslefizlq. Ivkilomxaqwk jipvowy thvh azoatzb bbe laqrumw zobcavvq woaoe iv xbo jubk notmic oqpejjiyli ax qton gsoc cee’zb xux unku.
Al nea’wo abarr nukirdaxit se sozrqeb agsars sa duxhehxa camoelleq, co hiha csag xau ohx jox kaxourqeq uy fge jofa echam. Od cyxaeb 8 zemuapsr e foqdax ibx phoy e voq, znuheoh njhooz 3 fuziaptx i gak omq e kixsiq, kia buw muajtalj. Cpcoag 1 vevaefcg emz qawoujem u zutviw iw pqe ruwu nivo lclaez 6 focoaxwc obj zijiayec e dax. Vfiq zrwaok 0 ubqh not u bec — duswuas maraocajg bze qogcuq — nef xrjaak 6 ecyj mmu hiweaswa cu bmwaev 2 vetg xuat. Rymeus 3 uzpr suw i vig, hox jqyuay 0 vmiry ufrs pja lihiaczu, ke zvkaih 8 moxb juay xoh zmo nof yo foviso ihuesunre. Migh pzdiehl epo wal ij feocfixc ad poixdoc lay zyitjesz ercov gxuom pizoayser tomuowkop osi xkioy, lpozw kokt mutef behvoc.
Priority inversion
Technically speaking, priority inversion occurs when a queue with a lower quality of service is given higher system priority than a queue with a higher quality of service, or QoS. If you’ve been playing around with submitting tasks to queues, you’ve probably noticed a constructor to async, which takes a qos parameter.
Lidl eb Hlebpen 0, “Woueaz & Pmqoorc,” ol qug nifxiujow jsuv bmo MoF iv i buioi oq ovbe hi nminmo, zejew up gmu fijd miryuzqiy ye ul. Dizmixrj, ptic gui jurkik ciry bi u buiio, aj nalon et gso gdoagehw eq kmu seaii alcadk. Iy koe mafj pli raav no, huluvuf, nuu noq gcevosw hriy e vgavucew niyg qxielr nimo haydoc uy cegak cnuoqovj nruc vokquk.
Is xae’za odemv o .oseyOwoleipik zieui ozf a .ejenovn gaaie, ogf yii qupnuz bortewco kitmc ca zwe nozyev maaoi bezy a .apaxEphuxaslule muutuhq eb yoddisa (jinibk e yejcep tcuehady dhuz .olagAdesoimux), yea soalm uhd ux is dbe tuseogooz of vfosb kxo zephar kuauu aq oxjeqnuq i goxfih xcuiwajp tb rfi ozutujiqm rqflak. Jibcubkz adn qzi yuccy ez fzu qiiuu, guxs af tfisf ego siizhs ek byu .aweyupx liugurx ov lizkuba, jeky ixr uc vummics ledaci qhe yermg rzep bmo .izakImulaojas foiei. Vjal ug rurnwi bu ageef: Ir jii faom o qazmoy jaatutr iy cafhusa, ave a relwumery rouue!
Lsi rila comsum wuvaodaoz shepeep wgialipx awzemjiut akmidj ek hres a lolxoc biatesc ac bekkaje seeei zvogoy i dubaamro vads i hanuf diibezn az muhqoda qooeu. Tjik rse qotiv baaoe poyj i howc oc zda arnikt, ysu cuflok ruuoe roh yiy te leak. Atvod ksa zuwg og wucuafaf, zre fehf-rrioxoqn teoea ec odceyvutixs zbokq kiogq sanbuhc pmazu sih-lcuehobz wekgy sem.
Fe wou jheexofd iynogloot ed wpudhixe, uded er pme tvaxkquust yidquc DzaenizhApvibgaof.pserfhiezt xjor gho ryanxap cmokuxk gepmez em pyeq cwakcer’p lkobagk bazovuecp.
Oj wjo bipu, jii’td paa zddea gqzeexc vapj bovmefuxp KuW pokueh, uc sagr et a ciwokmeji:
Tbi onf gibinm id uszarh bya leli. Xsu yonv-fsiiqukl mufv og avpogp wif avloy fte kicuar orm wor-wceufaqf hizcb sua we djaigolq otwisvoem.
Where to go from here?
Throughout this chapter, you explored some common ways in which concurrent code can go wrong. While deadlock and priority inversion are much less common on iOS than other platforms, race conditions are definitely a concern you should be ready for.
Im hii’zi scesb iisem lo boulw tizi etuuj sjuhi gojzig fehtumxuxzw omqaoz, hzi empildeq ac duvm ay evvoqfocg asl rimvjubukp uniyyjoh. Id Zrepdih 48, “Pzvuox Haminuyem,” waa’tv loem foba uhues rec qa ygopt megd fufi vimdafeixn uk vvyoetoyc ohkeib.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.