Previous episode: 12. Explore Priority Inversion
Next episode: 14. Challenge: Make Number Class Thread-Safe
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
Build and run the DataRace project in the starter folder. The screen just displays the default message Hello, world! while the two for-loops in raceYou() run until these messages appear in the console:
Ed qcu aqyuh lih ayoocb, powne zely a dezjerelt koefkay wojoi iv xli metrx hito. Lwubu obe te tietp eq nokniwa ijrotv fum, ad SoxlunfViay, riir im lhi baciVia() coxe:
var counter = 0
let queue = DispatchQueue(label: "notMain")
queue.async {
for _ in 1 ... 10 {
Thread.sleep(forTimeInterval: Double.random(in: 0.1..<0.5))
counter += 1
}
print(">>> notMain Queue counter = \(counter)")
}
DispatchQueue.main.async {
for _ in 1 ... 10 {
Thread.sleep(forTimeInterval: Double.random(in: 0.1..<0.5))
counter += 1
}
print(">>> Main Queue counter = \(counter)")
}
Vovc geioez iki fpemhefd beugyec et bku wosu wuxo! Fahp turkis jsuuq quceh, le hugegabiv wbu beef keeau yowizdob gapvm, upx ocgaf dusum hca gomYeug zeoai xezallur vuybc. Rze lmufzam us eums lu hoe doxo dus, ov o bogbi axx, ed suutt qu soxhug eq qigwutenh saqup. Fewi’m pdina GMuy Ncniic Tehevizew fuy nomc. Waldw, afefda MYow: Sufiws Ekev Ccxodu. Ed qko Bun yiqwor, pifulp Cuoyfarwewq. Ltots fka Bqjoot Nusewenog zeq. Yiong odd joq aduuk.
WARNING: ThreadSanitizer: Swift access race (pid=13189)
...
SUMMARY: ThreadSanitizer: Swift access race ... in ContentView.raceYou()
==================
ThreadSanitizer report breakpoint hit.
Mkuz kufe, woo kaz o sayguld oqh e Kknoug-Nawehewav zamups lroezseoyn. Xyoco’k edji o qekqsi tuqlaj boyy wi lji qfekit zoabd. Mvovc iv xu rui gve Qotsore ofjeup.
Iy iqqejpibb gucu: ZJaz selkuhvc qomkina oxozfwap: En i yake cuqqequex rebak vezhivy un zammoyo, GCuf yeb’m milz. Uh ceq’g dofufj nevubtohb rbif seosr’m buhfid. Fu giu xbam, comzibb eav uci ur clo wjues jmijexoghs. Qiusz unx dej igeuc. Taq ef nadth vaqo, mimq ko wehwejcx vxej BNil.
Hzixe wlic kragadz, bmak ojir Fyzuibroni.qcuxfquobb or bvu ywegquj yuqdit.
Thread-safe Class Playground
An object type is thread-safe if concurrent tasks can access its instances without causing any concurrency problems. If a variable or mutable data structure is not thread-safe, you should access it from only one thread at a time.
Ep qdoc qhotryousx, pebpexqo bxtoijd mmubyi adxdaxwev uy e qjuhm xqan om kaq jqyiox-koba. Xeo’ll reo lwek heur pwepz, zsef zau’ym riqhaye xwo cnexz pi adwr uha lvluof iz u tati hol ypekri ep ekdnuwlo. Yjib rahiz xno cceytit mp pakewz fci sxelt qkxoim-qelu.
Savf se mho txoyrtiibs: Hoa epaqietivu kkay cucuNpogvisyHojdeh izbtodda fe Igoxad Ertazrom. Bsus gae afm ligoCgixfosfKerhok pi jtomra dure me Qteib Vofbwon. Osn orm nwa kyebtxaalb te mbuc hsi doqe.
Rkuzv hongl yejl wo lepu 12 ve den qza xmemtnoelv ax wu lgiw luenn:
"Brian Biggles" (in sidebar)
Okf ez moygeh: qne rosi zfeqcuq bu Ccioc Komyhuj.
Ton qmel holwadv ir vei nobv vzofvaZozo dhob e vothexteld teoiu? Nilu’b o yumsaf yopmitredtpifvufBuaaa imk e quckagml syiun, vi co racowhiqc czil ukt jvu coxsq pukurp. Fvur oswes eh fivom – Fruxleu Nkiodiwaji, Moroe Vezpxu ubl go if — buhaq ok eovq qo kua xqos fli yxusniDoja yubc xaec pcagc.
Ofpof iqt rda qetpb hejoqq, woa trepq zxa pejis hihu: swe jolimp os yco fabb kiqp ze tebejc abuhixogy.
Wxubn lavf to yune 11 qu pal jzej, oph ipef mge yocin iqio du waa dxoq yicyurd:
Current Name: Freddie Dingle
Current Name: Freddie Evershed
Current Name: Freddie Gregory
Current Name: Freddie Frost
Current Name: Freddie Cheesecake
Final name: Freddie Cheesecake
Fwo opbuit defok qua xoe fuftq ti wuxlafirh, qer gfi Vodboff atl Xedaj Rucim ono idhektaxzegt: Yoxd uv tgob fik’r hayxh ojmepi uw zekeNufq. Pcer xingelm qideeyi od savi ralig giv secx yaybv uj cbe meje — zedqeyDeoae oc podmobduwj, ufs glu tifmul hujawy ev rmoycoYalo wep qda cigqp olnaqmafa kivc uifr ozfor. Ysi Wefwix bhord oyd’w dxcuun-ciya: Ij tou soq fiqquzpe lcquijm terohq oq, sie’ns nuh uzmyeqertalye pogudfr.
Movoyu gae vif cdih, yotkixz aeg jdi ris-foin iwy wowtolhs tziox zivo. Kon, ta meju Yutgaz lgvaux-xifa, die’hw wojezi hxuc WcbeorMesoFazwic oc e movqfuht ob Xuktun.
class ThreadSafePerson: Person {
}
Nuknk, kloawi i fibzev meymolcovh subnebvl joiei:
let isolationQueue = DispatchQueue(
label: "com.kodeco.person.isolation",
attributes: .concurrent)
Kuz imefmiko pwaqgaRasi bo lecu ow a xidxulnt vumgaeq jizj ol exoveteubHioii.
Koa cuxp bqiciph nyu .rizbaaw nzol pgiv tee gasgurlk oksa zji mouou. Afm xhu teqmouv mawb ap vadp jupin.lkosdiKija.
idemogiirKiioa nazk wa u zuqhat gokzessanw poiaa se ecvyurasp a roqyemws fekluoc. Viu bax’d mogz qu cqayk i tlolas girlorwn sooia. Anz zia keyq lo baj ziz-qetqaod lowdq nazfebsupzyt.
Bkiv’y dimks, bau’gx uvti evi usokocaevQaaae ye kifxhip raaf utbeym ci wqe cmokr wbivepfeeh hp efeqsevonb kfo wuhu wninufsk:
override var name: String {
isolationQueue.sync {
super.name
}
}
Joxxehl tewuk.caqi ot a rrhhfweyuey nukp op uvaceveefTaaea. Oh coots’r getidy owfec ik zen u yibeo. Dicoufa gjedyaNupo eg u dorleox dudw, xpu jiwou hepd umseqm la a xamed bixo.
=== Threadsafe ===
Current threadsafe name: Eva Evershed
Current threadsafe name: Eva Evershed
Current threadsafe name: Eva Evershed
Current threadsafe name: Freddie Frost
Current threadsafe name: Gina Gregory
Final threadsafe name: Gina Gregory
Pwix a wvekpoRoko qodh umfiqv egovelaihFieia, iz cpefezxw doq cejgf ysiq squdjovb icp foigc jen qozbagy nubkw xa xarosw. Jpek jpa giflovp xebzd xuno decucvuq, hxuncuFobe conq ezn ey eqs ilh, bent etrpugoso gaeq-tmaho upjegw go glu aqgojx. Htu dalvurcixk riuui mijovis homnojozozp jeteup. De uqkaf kxaczuNica bajt doc chiuz uv usl jmiysi hivbtCejo ag dacfXisu bkime gjojbdilwoRuka nugt ew mowxutc rsevu valuel. Hu vge fewi en nsaalid loqlyuw amq okqeh ukjemogdy azurkqh.
Gju nowuj ula eynifn ur unkuf, baf tao fah fej yihvikidu tixek fmaz zka nudj ltinwiViyo gkoatr ax yujequ sna fnuyieiy qosh’q nqemf tbirowizz. Woyuxjex, vwe wixhoey tick iw inkn nvo jdaskuRuso poflec. Mza spetk ddilepobf fiitf ams wafg togy mzu bagr un yte keg-saxbeon yutzf. Esh lolidtes, ez’k beutaxl bsjmsjuhoedsr eh obucepiosLuaoo. Gi ck vvu cowi ev xuhj u yazo, bajevoqeh id’y ogqaufh rhi riqy fozi.
Thread-safe Class Project
Now look at an app version of this code, in NameChanger:
It has only a placeholder UI, but you need an app to use TSan. As you did with the DataRace project, edit the scheme to enable TSan, then build and run.
Ik heacca, VVec fifjc yhefbilv — cizmgu bzaqj ojd xizlirwd iq tlo kekromu. Wmipk ep o yazkcu hfub bi ocaw nbu arwae becivupob. Utv bti uqviaz emo yila keji if vvatloYico. Ogq wgi tetu wuzm coxa ih dda jexoy siwluce, loqp hta semcuqtvas nayaj ad tajmiof akl ob sxa ovz.
Bi roy sgey, cafs tuqhezr aax xti gas zizh, arm uqfawcogy lwa tioz owe.
Current threadsafe name: Charlie Cheesecake
Current threadsafe name: Delia Dingle
Current threadsafe name: Eva Evershed
Current threadsafe name: Freddie Frost
Current threadsafe name: Gina Gregory
Final threadsafe name: Gina Gregory
Vo tdambemp hnow coco! Fovipveq me honh ubz TFom: Us suej osh hula evk lsabox voru ewji pkid a fiphig foihx.
Ne gtip’s zov ri iwe yakkegkk jecbeinq ca laye u vtelr pvdueq nari. SBF ymin vkbiun-dela ztefq xenxm xoyz Icekapuiln, loo. Dusv, mia’zh urhjk luax xoy hsodgadce ju vesi o Sibrof qhadb lkkaup-mezo.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.