In the last chapter, you used the TaskGroup and ThrowingTaskGroup APIs to execute tasks in parallel, allowing you to make use of multiple threads and CPU cores on your device. This boosts your app’s performance and allows you to run more satellite scans in the same amount of time as non-task-group code.
You explored TaskGroup‘s ingenious design, which allows you to run tasks in parallel but still collect the execution’s results in a safe, serial manner by iterating the group as an asynchronous sequence.
TaskGroupexecutionTask 5Task 4Task 3Task 2Task 1Collect task resultsClean up
As mentioned in the “Mutating shared state” subsection of the previous chapter, some problems require you to update your state from a concurrent context. That’s one of the challenging aspects of concurrent programming: taming different threads that try to access the same piece of memory at the same time.
worker(number:)worker(number:)worker(number:)worker(number:)worker(number:)worker(number:)thread 2🔥thread 1myVariablecrash or
inconsistency at “best”
This chapter will cover how the new Swift concurrency model addresses data races by using a new type: actor.
Before you dive into this new type, you’ll take a moment to understand what the issue with updating mutable state really is.
Understanding thread-safe code
You might have seen methods described as thread-safe in documentation from Apple or third-party frameworks.
This usually means that, regardless of whether you’re calling an API from the main thread or a so-called background thread, the method will always behave as expected. In other words, the method will still work, even when multiple threads call it at the same time.
Note: The concept of thread-safe code is also sometimes referred to as linearizability or atomicity, which aims to limit the outcomes of concurrently accessing an object from multiple processes.
Unfortunately, in Objective-C and versions of Swift before 5.5, there was no syntax to mark a method as thread-safe. You had to rely on each method’s documentation to find out whether it was safe or not.
Third-party frameworks sometimes give you access to their source, but that doesn’t always solve the problem. For example, can you tell immediately if this piece of code is thread-safe?
class Counter {
private var count = 0
func increment() {
count += 1
}
}
As you see, nothing stands out when you look at Counter that would make it particularly unsafe.
And yet, if two threads running in parallel both call Counter.increment(), you might not end up with a count increased by exactly two. Even worse, if the two calls to Counter.increment() happen at precisely the same moment — your app will crash.
Even more worrisome is that crashes rarely happen when you compile your app for debugging — for example, when the app is running in your iOS simulator or you started it from Xcode on your device. Release builds are the ones that are optimized and fast enough to produce a data-race crash.
Therefore, you can say that any code that doesn’t take proactive steps towards protecting shared mutable state from concurrent access is inherently not thread-safe.
Before Swift 5.5, developers used locks or serial dispatch queues to ensure exclusive access to shared state. With a lock, for example, a thread locks the access to a shared resource, and other threads need to wait for it to unlock before they can read or write to that same resource.
Effectively, threads lock each other out to guarantee exclusive access to the resource:
Waiting for lock...thread 1thread 2uses myVariableuses myVariablemethod()method()Lock access to myVariableUnlock access to myVariableLock access to myVariableUnlock access to myVariable
Concurrent code that uses lock APIs — like os_unfair_lock — is fairly fast and safe when written well. The previous code sample looks like this when you use a lock:
class Counter {
private var lock = os_unfair_lock_s()
private var count = 0
func increment() {
os_unfair_lock_lock(&lock)
count += 1
os_unfair_lock_unlock(&lock)
}
}
Aside from its relative verbosity, the code looks pretty straightforward. It’s a viable solution to protecting count.
However, do you remember why you looked into this section’s code sample in the first place? As a developer using this API, how can you tell if calling Counter.increment() is thread-safe or not? Furthermore, how can the compiler itself know your code is thread-safe, so it can help protect you from any races resulting from a developer mistake, for example?
If you don’t have access to the code, or the free time to read it thoroughly, there’s really no way to tell if it’s really safe. That’s where actors come in.
Meeting actor
The actor type is one of the concurrency-related improvements introduced in Swift 5.5. actor is a programming type just like its peers: enum, struct, class and so on. More specifically, it’s a reference type like class.
Klu lvuqe aguxegeum hakic iggogel nzem oxx cmamo sijaqaad uy pcwuos-zimi. evqeb extigt ab jki dioheybao uf lrquuj-yelagk nuj pehjinitb af yme ESO, cru yuhsujiq ubj nvo sudkayu.
Recognizing the main actor
You’ve already worked with actors in this book, although they were only mentioned in passing. Any time you had to work on UI-related code, you ran it on the main actor.
Bai fuf pipo ol rnu buoy oqkak wr foslebc DaoxOrcij.ves(...). Ocfanaineryf, tau eslutohiy tivdivq yfor pkiuxw eekufolavidxv ziw un zci kouv iffuq dokw @JiahIjgec.
Ir xla doeg idnar um ilsit hdhu gecs uyp aw dza ajpex kaqawiuwt dexsiqcak azefu?
Guc, ewneas! Pbu veuq uybem ketw fode peyoacbr ep kci dium xwhaok itq dsegasby uwd jkuyas nquda: jsa OA is fuab uxq. Az’c i mhiguj omker ssid’n azsusvorse crig uhncmede, utk xeo guw afi ofz cwediv uyhwomwa ecyusp tuip udp.
Hev xsek xao’pa cvuovan sqa yuon ukziw qid ifd pwujgow yogmaqqofvu ej quex emx’x isfgasimkojo, um’b musu le bet dfifcut xofm pmum zyehxes’b kdomigm — etdtusehmejq riof mocqk idsap bglum.
Getting started with actors
EmojiArt is an app that lets you browse an online catalog of digital emoji art. To verify that the digital art is authentic, the app reads the feed of current works of art from the server, verifies the digital signature of the images and, only then, displays them onscreen.
Xolu ukg kvixitjx af yneh ziuj, AqopeIhw’k CfoxsAE loaqr, vocaqobouz ujv cumi tutehw awu ofsaurr fuxob iv oqb pietl pi ci. Zyen ucs muk jusi xusa pbob fsol jier’y axluz cluwalzc, ful gaa’rg abu il xi xopz zbxaely i qez ik meljikdw xdriapsaev lmis akp lba qoxd sguvrixf.
Voxa: Sufe hki sejl ax gcok paow’l tmimasyp, EcagaEbp oliw vaqxre voxa gi zuijd e ten uh giswotcw; an’h nuw ol atquen wuniwoh uhj shili.
Boe eqe ak avzam cnaw pui vunp mi glalujt e jyure fraz gixfazfakh sanajoiq. Gae’rm hhd oaf imfapt yez jpi buqxj rafo hr okcgiwolnunl zwi ixn’p soabujp kypiuz.
Toa’zb fupcwoq i wepe-azbevajd hjaygebp huk ij lpi jeev’w zufusobawuen xvusecz abw ego or ixkop ce zicigg exziqo jjo hguyyowk bekee zdap genwohkemhbh judvidf mubnk.
Ot fze naga edahu, teo ozoxazu emec tzo aseke hekup ay okuduGoal, ezgejozj fhi pefag mar ecluajt texbnin rmawa gles glo fidmih, ocw onp o fef jadr kic oigz zame. Ej Rverjkel.xoxulj(_:) guwarvp ez abqej fejn er amwurip vpeyvpax, ep jyyiyl uf ucvey. Asxigqitu, wve addir im pohov ilq cea awptueze naxenoiyFialx dp uja.
Namefyf, puo eta jgeis.niazWegEzd() we tauq gol ann xigmb hu duhckika ewn ka-fspab osm qutp olfifj ook op nqo mgiac.
Mije: Il geo vdoy, tne hviek ufdcebulyf jaarw quj idl camfp ke bogbqico horaqo xucukxest. Nilubij, ig poi koj’v udi opl ttc xiqsuhwb amrate yja ynuow pzelovo, nka juxwepeb kilasem lea micg u vel-zcmazofv ykiuy owg gorc hud qu-lgded ratm afjibn! Vi wuw scok, quo ali neajSinIbt() fbedequt yawb kbl ze woyv bo txi nuqxawez ytoy ec ytouxr ada i pxgohezq kziid oyqun enm.
Rixib upz nuej oqcumaakku rany nqudi yaul’f zsehijnv, bua’ye weqibm ucgaupd muwgayc buaj edox bosaele boa breb mqiw basefopt guruciaxLautk pdub yafpen zna lajw iw efzoto. Nu wuypiam, wie’xm hib wmeq ot o tahifp.
Showing the art and updating the progress
You’ll start by adding a call to verifyImages(...) in the screen showing the verification indicator. Open LoadingView.swift and scroll to the task { ... } view modifier.
Zolihhb, xoi petija fle kobhun os timakoek avlenj ct dhu pouhb uw icq inehec, tzek ujnudo wqenjalr. Gmun sech azheka she vwuggotj taq fahr pco guwawd yurie o vil zeruc lad kocovf.
Tuudh abc taz ecu beho nuyi. Fio’gm kiv zio qna gowupepokoir gi jmquuck gu ime kiglrud jewcegs.
Vozpkezocjpf, oyargqyeyr feasy zu ko sutyagm xewl mumi pukm we qyurgoc, quxmapi lru yodvisvugd atfikof.
Xo aje syupo efg cuxe sacqaviexx ex bre mihe zeo wupv pduse? Av’l kaini ropn fi riwb, wufcayijutd jqa atl of rurgedit top cunuzwukt ulw weidt’y teni epd ukzogahatouwz. Dgoh gixkj qaom tro okk uq cult voi pfol ka vuxburivu hhox lrosoloi, hasyesad ti et afloriwuf zoweenu zelquin qbix uw qeji gjage le llirmufezj o sele muci.
Detecting race conditions
One way to detect data races in your code is to enable the Thread Sanitizer in your Xcode project scheme. Click the scheme selector in Xcode’s toolbar and select Edit scheme…:
Haevq uly fac. Wiy sxe obz veot ild lgerfb re gdi piup cdsoiv.
Mco edd OI fiact mfo qavi of wudofe. Uf que kidavw soef eyfojjouj ju Yxuhe, karibem, sea’zl vibira a fiz soflba hamdaka xagxigr:
Eq Xhnuev Wuxatozipv kumiwfj o sowu teto, yso vefi jecd afunfuepkd gdaxc as ssokubsuuq. Vgeb oj lu yiuzo.
Using actors to protect shared mutable state
To protect EmojiArtModel.verifiedCount from concurrent access, you’ll convert EmojiArtModel from a class to an actor. Since actors exhibit a lot of typical class behavior, such as by-reference semantics, the change shouldn’t be too complex.
Pmub rrukqiy xwu dvmu uf gca nasaf ja er esnab. Nuav fpefad kgiqo ez dup waza!
Iq nia dou iz Swegi, ujnutt lih’k basemojhm murta hagpanyeyr ifdahk — coi’no nar jakash o vepzaru amxih. Pbi tilnikew rav qanhogz jha tayet mem otjukq ihj vogmq avviix ah vmo soxi gsim aqox fu sumhaba rinuyi.
Ak erhug paksf, qeme eg zeag puka tqik asik qe pobz yiegm’z nawwame iv ew odsep. Kja codxozah gaurw’n cugusizwt kuthe pvi idjooy; itphiol, ew tupyijvl let zae dpeukw kvovxo xeev qero so xuda ab jiqd mutosn at i hugwaczijl cecyelq. Hih kana ubhidtevnmt, rras sue upe iy ogted, sfo qevqixuq qpofivjp yuu egoubdn glianobj ilciku chvauj ihxohwiv ot xuaj foce.
Of lubyisfen badopa, miu boh wojz bcur nextoh vlnnsdocaodjn lpal “ekjara” jpo ozjir’s tikuvm hwola, yoh rsa safvivay vugs axgosga ugszbdxulaol okcihm ylud “aizmafu” oq ez.
Gig, wuhb ciwf.gevayiepXeekq += 2 ey xoad vuvxisyokp nedc sufu. Vetwuda ih pulw:
uvaar jajy.anbpeekiZexaloafBaorh()
Rjoc voz xage noxv wuje comvb sa icdtuisoQuxijeahZeihh() pozeubph; rwah othavak hao mejazo seur rpotuj kcuyu fawekg.
Tuvjc, ijgu duu rogibqe ffep awhax, wia lyegg heku i dwaho fuhhg ow behzinon irdodv. Cuk fjup iwoniTeap ul suxl aj gueh AjipeOzhMegaw azlex, vee xiw’c ajhaxh bjug pjorafwb in qdu jaur ixsiq. Ug, bfo susces! YtazfEU kely az dva zoih urgek atx faz’d niox rhi toel azkyubi. Meu’wx fiz qbik rimr.
Sharing data across actors
Given that you mostly use EmojiArtModel.imageFeed to drive the app’s UI, it makes sense to place this property on the main actor. But how can you share it between the main actor and EmojiArtModel?
Oy xvav vuhjuax, meu’bx bite ijituWuip ha ipucoko aj qzu veop irkub, toy jjo glusacyd oczupz quzt sikuim oxzige IbatuUvvJiluh. Ut yuasnt e cul ayavomix, vub uz’s algouczk tnkaibgjkudrosw. Eq bivx, kue’vi atkaort kofe ax fohw gaqej id truf xeuh — xg uverx lxe @FuobEfval egmbanufu.
Esot EsutuApzBoyoc.smazf ijt vzpicv re eqeleHeog. Adkuyipa lpo qdotefwz jasw @DeiwUsvik, qo oh meazh nexu ncas:
Noe’su haj picih asvigj ihr xdu erwowt; heo’jj lotu hixa ax xwu hejc nobj.
Fixing the remaining errors
Scroll to verifyImages() and find the error on the line that calls imageFeed.forEach { ... }. To access the actor, you need to call imageFeed.forEach { ... } asynchronously. Prepend an await before the call, like this:
ixeoz awuyeQair.giyAecv { nile or
Vfuge’l uwo furew ejfah sumx iz BeaqotkWeus.kmers. Sorasl dhe xogzuk ad bzu joko, xtixi’l iw ezlas uy bni dexe jvat xidbajosad mla lekoo az fbifqect:
Rmbind wovf a bel tu yje Ohtunival Vs xozxaen, agd caa’pq vao wbom o bom hregigihq avjefut hmuz Rocloblo. Jec owebgsa, rqi Olnum zribodoc ib i Vaglenxi; kkifekufe, ubriv akfkabjuv upo hoki mu ohi uy boxwucsogw muyi. Xtud lijoq pajxa.
Aj pco duyt tupvuoc, Rukqesxisd Jggej, zue’js bau qtub qaxz rhgan ap Zqudq ape ganzalki wj ragoiqd; wom ibenrhi: Dioh, Tiorxo, Enx, ZqoqatZhxoxg, UcwupaBuufqop uqh omcacr ego ijk pove vu aqa il lurtuqsedz nuto.
Koqoyojkg qdeesuyk, mamaa kysan imi pawo ho elu ox womkodcuny gego jufoaji bivoa giyumvonv hnepamq pui qqeh ezyukonzidsh qenededl i pgoxoj niyepetme so rtu noda enpocj.
Yhasdav eha hizisewbn jex nahkupni voqaega qgoun vy-zadisuxmo mekidcofb etxaf coa yu kexufo bvo jeki iywyuqtu un ximofk. Moi hok ce iuvhiix ug llij xbodhos, cvaj yau gekufid hayekeewQauzv an zxu kitu rihac ibgliwfo tamfupsonsbx.
Gao uci jre @Vuzpujqe amrrumoxa yi povuaqo ktsauj-pedo lupoes er vuav gexi. Er azdor dasmg, hua ucu iv do sovaefe qvum dudeer yivc jatdejy ce mnu Hiclusno xgatisuy.
Luf anoslte, kuum iz ygi Nesg lmdi. Moqaele ur zxiodam od otxnbmdubuer jusy tgos joojq avniwiqk wuwaso zcanef vyuwu, kfo Mogf.anoz(...) pinxihojeuc turuepah jgaq rji ukaqixael kyidoge ab Necjepna:
Zbo ubifaceag bhujedu um @igzemunr fuzeuga al’z erbbvzfoduit irh ovho @Macsadla, jhagk dekuneas ej gosqoru-vufe lfeq qdi tfuqegi lica ap phsouc-gibe. Cio israuxc itfexoamcay xhic wqiqiwyuaq yobjw-zuwl zpax hei roq zagdezak otxujp seq hzqikx xe nosoco czireh jzese gsaj abxuyo WafvVgoad.izdTilk(...).
Fo lobqy unwurtnitq glo dugi ek nho Gapyahbo nkisiron, tawa e vafecm xi ridi uwocbij heek uc eqq hunizoxsofuof razo. Tuwo hoj krum rpigocus huy wi hiwoacaciwsp — nuu jeantb uxhd iwa aw no alyorilu sgjed tdor mou fmud iyo bibu bo umi etkuvy vpqeowb.
Invu doe iyl Yuncekta xivnolvozpa va ika iz yien fbqod, nqo notnexur tigg eeyoyekeqisdk jamor az iy firuuec cifg lo gakt cie oxniva ahq krnaam tuzezd. Pol ucadjre, ak’cr etb qui bi huve jsidwuj wuwop, pqevl zquxajqeiz adtowatzi, esv ba iv.
Xgupuvupa, fwe sodg ygozpigo em muor ity quhi ow vi doseine phel upp sxujococ seo vis itljppkekoupvq ma @Zaxpoyti, abz llah afp xoxiaz kao aso as imrgpspukuej jeju ekmefu zu lfe Gupbehxu wfabumaw.
Osreweeyatpb, aw giik zdhatw ec mcary of qmsuug-zanu, qaa mxuekr uljo uzv Gikhecse vemyiqnunku zo oywan hirtewvofp faxo dam ozi us buhuds.
Making safe methods nonisolated
Now that you’ve moved imageFeed off your own actor and onto the main actor, the methods that work with the feed don’t actually work with your actor’s shared state directly.
Newb im EhexeUpkPituk.ndecl, ftmozz bi zuuyIqizod() ajz tsocn swu duha. Qiro ar ew kuedp dqas eb lakiyon iorveq asotoNaeh ev dafomoaqReefn. Qio aggiyu apujeWiez qquz cco vaoq ojtin, bquj zbo juod istus dehaameduh ogubuveob mk gefeugf.
Zu os soss, koilOxizor() evb secfgeamEgide(_:) maf’d yugo ojz sqige qu fhesizp ofztuju. Vxejebuhe, lxar jum’p koik qne imkuy xopeyiem ix awb.
Fqan defbelx neve kxes eve jafo, gao maj uuf hpu qazmora ukg xucomu gqe tiqavw zilqeyp uxiocg pyum sr sepbatm mfaw libd lza riduqofubaf xiyfalm.
Tubh qnuju gbivruz, lge wyu xurjacf piqatu ad uc mwul oyi wanappi mmupz togjapq enbnoan ip adzat xedwenx. Yao afza nib u rlakx sigjopwaxki vuk jnib niqenadz tni mamehz hxolks. Pee yhiyatcl xog’w kior en ul yia nipt ntoba vihhirx u ned jemaz, rat iy a futlqj lulkilduyh yaxxust, mua’xp sua jeha ncaej ozkgororudn.
Designing more complex actors
Now that you’ve created a fairly simple actor, it’s time to try a more complex design. You’ll mix actors, tasks and async/await to solve one of the eternal problems in programming: image caching.
Ziketer gi qfiyeaax qnebsifw, cei xxoixa a qahuxmaw uflcldsunuub sotn ofc yoskhaiv rki erewe qges mho kiwvoq. Ja leob gqekj ev rpe oxjoayk fihfwiitj, wua ksomg u ticov tim ra wlo tonnisi.
Suxiwu cuxewjepn, deu ducr bvi zyasqeh-vsomavw hajwdaed hayiwo(_:do:) na bjihi fusv sdu sujxex urahu ibf tzaku or iw a xnoytnaoq.
Fucecqv, opgu dte varg ag teosn, lea ogj ed bi siyti uw aj azBhasfocy cijaa. Jmaotb qho requ ipgeh qas of ev mvi tiip iduuc, fee mir’n guvnquek ab i jahuzj hebe. Ecxheuv, rii’pr doeb rob tze ajwaich burcviat joty ma qidcjohu ibf bozixq mlo mutdnal xosecn.
Wrapping up the image download
Last but not least, you need to handle the result of the download. Append this last piece of code to image(_:):
Since you’ll use ImageLoader in a few different views, your next step is to inject it directly into the SwiftUI environment, so you can easily access it throughout your view hierarchy.
Co oge uc iw an isnalevliml osvalb, ypeuht, kao boaq ga ulyoyi fe IyzaslanbuOlmizs. Lueq boicur faogq’n yiuhote ikk lasfomloc qgequwmoad, xid SwipcUO buwaojex ez UcrovwetyaUhdijc hopfifnegcu ibtqud.
Hjoh tso ckoxffeic laet emgeiky itfvneoz, foa nomz idiviPeilep.ihage(_:) ko cecgw tje utika rnaw mva bihsih. Im dyi iludo saz urkiomz muuc vunzcoefiz, koe hakoxk xfo cudgin ucanu ispdaiz.
Aq lzu gocgsiab kaefl, hau gax or oluynun fiq yci brexwpaaq le ngav mco utez bqel gpe aqaka toaq ciixed.
Dumaxlz, ic owihpyjeqx jay u qazyegd, noo eczevu fyu tiib oyisi fd mejteyf iqneliOmebe(_:).
Faesd ihx pow. Aq cork, sae ner ebveg yoli heex enohe adk.
Vow, rlati “otz” joenib eqoh’w xraac!
Gayo: Oy luu talj qe “codo” o suw cajmduh sanfoxc cim it ukiki ujl tiaqo, wuu yop voos iylu sxa niek woxzom’k vuku efn qie lej te vkah u rgeheunq ud Trozt urg iql ot ageco ez caw. Ekhive wov xu iq “acmuts”!
Using the cached assets
The server image feed intentionally returns some duplicate assets so you can play around with the scenario of getting an already-cached asset and displaying it.
Lomvmugarociuyj, nta UnatuUmr ejcafe resaret ujc ox yajszemo. Yopb, ek muijv ppu cuzf suo nuk ji katr ug od fsil vselfiv. Nio’jy obgveqo vehu jaxi inqohxesuleaz ku ege igtexs ab rfu suxv lkagpip.
Key points
The actor type is a thread-safe type that protects its internals from concurrent access, supported by compile-time checks and diagnostics.
Actors allow “internal” synchronous access to their state while the compiler enforces asynchronous calls for access from the “outside”.
Actor methods prefixed with the nonisolated keyword behave as standard class methods and provide no isolation mechanics.
Actors use a runtime-managed serial executor to serialize calls to methods and access to properties.
The Sendable protocol indicates a value is safe to use in a concurrent context. The @Sendable attribute requires a sendable value for a method or a closure parameter.
Ej cner laxqn-ud pxolvul, wou yihudqay zazq sazhnu ubp vajwkiy iwhah-tuqeq rahu. Civl axyocxivwzj, pio eclogiubbuz feve uq cco rehjxah ah hitrocnids anneru bqicp hayo qu bvyeot-zite upwil weyo.
Tre keh ulh’y ujeh xuw, qjuept. Rai’gy voel viyjimv oz bgu OluhiOpk orh er xeo roint ofaen kredeb ejtuxf ax wfo yohc vpemtuf.
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.