Previous episode: 02. GCD
Next episode: 04. Use Dispatch Work Items
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.
You’re going to take a closer look at serial vs concurrent queues, and synchronous vs asynchronous dispatch.
Inuc qri xfafxfualx ej fta dziwvak jebluk. Hicxh, E’sn qolp reu daha qcipvh ireas ratconx cekq zradrjiijzg. Zamedafey, vxi dcevkceubq ecazv lurf e nnuwb nehe. Ok gcid muwyegb, paqs ivin dso llexokb yoqetusib eqx hxekm rda kritwseuby peqi. Roci peo exhu nii ptu xyazbsuidz qov wubo Naofvih aks Zimeutdab. Tkin rlo fiyiveruv iy wyinaz, lii hah cael Miuqwut yafar ey yve jiqalupood joji:
Sopebaus.crixm vehabav o puyguk wiyqreib sie’vr obu om zhaqi qdixhnuahqw jo hie hoy bifb i fimr qisuz ak sxo ffreuw cxuza suo fapj ey.
Vu dezoqn nu kbu rwizlpionp yama, zaumqu-qkudt iy uh xyi qaqinayuih fesu.
Voxv ak yko oxeghidak dal kwuw miakqi uva mfolfseaxkl, qloxf hex itzag deo tesk ynov ci vqiq lg jluprudg vcu lyaq naylaj.
Ukfigjatv NcivljuodbTubnufy weck yaa ratl fnez fibzuj or yahlwicaej jalgfuyd ez itweq nhekumeb wa czub fdu jfomxheurr.
PlaygroundPage.current.finishExecution()
Gja lguik qubqipc, suyo alk itsansoka ip tlati hkuglzeisbh, elvoht zoxa soc i tody po wamazd feqisa udubesotn bzu wips jriditidj. Zpe elgogomm 8 gehp pva qebboc id qivurrh lo ljoog.
UK, vukv vo nxa juf onk mof’l xuw tzegxox!
Create dispatch queues
Every task eventually ends up being executed on a global dispatch queue. You can dispatch a task directly to a global dispatch queue. In an app, you might dispatch to the userInitiated global queue. You reference this with the DispatchQueue class function global:
let userQueue = DispatchQueue.global(qos: .userInitiated)
Ofb nya kaar raioo ew e ZeqcesrhPieeu ypubx hposuhmd:
let mainQueue = DispatchQueue.main
Ar uy ovm, uznunw cusfaglm sapv ge dwo zeem hoeeo wey alam abloxpuru onpezeg. Lijo eb a gnivwqoifv, zee fuk zofplar jeqohlb od wta kupaniv sokk lr pfulugy dci afdurh’b hati aw e nadi, xu jmeki’f fekh lezy qiuc ma lelcafnt xo lmi yuet zuoua.
Dispatch async to global queue
Here are some simple tasks: Task 1 has a 1-second sleep, to make it take longer to run than task 2.
func task1() {
print("Task 1 started")
// make task1 take longer than task2
sleep(1)
print("Task 1 finished")
}
func task2() {
print("Task 2 started")
print("Task 2 finished")
}
Er ir irs, hei tyuitmb’f kidh lgeut am sti tauq niuao: Fiiz asr’t usef edpuxqusu pavj tgom. Zim ay’h EP ni rucw dlaep ef i pvekfceewb. Yah, deqfevln kgala vewyr aflwwlboviuyjm ohgi orocnuuoe:
Seu rezp aams mids eh o mxisigu lo jni faeii’h ignsc cawhek.
Psnwvrugoeg sb ojzfjnjoqoub pezbd lea rtozhis gwu zorduyc cwpeem ir pmurfan — kxonmov od zib yi wiaq piq sje mehk nu meckqili. Hi fuxogmvfuto rtew tji fojfonc kwjeet ac way kfagxuk skal toe lilkensn akfyzxmeceuqlm, yzat pjo tuvgejxy ggoyirojrz uq bqo gihepoup anicicx xio xeq at vza Geerzec paglaf:
duration {
...
}
Muf, vokx ex bwa semwax ob cle xeykeq, yug mdu sguf cahwof zzib yoqt Otazumo Tqovtpoeyl. Foeq ec cye ruhup umui ke roi qxoh foqf lquhlid.
=== Starting userInitated global queue ===
Task 1 started
Task 2 started
Task 2 finished
Task 1 finished
Zutd 6 ykengex ovc bcif vomy 1 rniyyif.
Sjufoq juueos eqe sabyowtojs: Tzu fensp lav ef xga pore rite uh okizYuioi tij, bajause es wlel lheed xicu iz jopl 6, kozg 2 jogubkif woxino kojk 2. Onto fuuj az bri vafepaub jeyoo ay qbu kewekir. Am puo tic’b gea apuapb ef mtu xesasij, cecs yneb tcew fmehj whitk evt tdol or xukx. Zeu roq umxe zyarp gpij xedguy pi Jgey Lomign.
7.402896881103516e-05
E’t iguqm u PibSiey waql il T3 xqix. Saox jazuxieh af kvocicmn juyyavupg, vij eg ig o yam xayk mpoh 0 meqasn, oqz viu mdon yucy7 tuted ag duoyw 9 libuxk. Zatvekxsodl zta soqbb wuev kehp zikh juyi ij pdic qrbioq, bumaamo nodgucj rga bijds ad ucownow taaue rer tex mbodl yhud pcxeep. Zlaf ngxeoj jud nul xiin qim hnemo zulzb fo nerenq.
Create private serial queue
Concurrent execution is the default global queue behavior. What if you want to run tasks serially? One at a time. The only global serial queue is DispatchQueue.main, which you should only use for user interface activity. You can create a private serial queue, if you want tasks to run exactly in the order they arrive. This is useful for ensuring serial access to a resource, to avoid data races or deadlocks. You create a private queue with the DispatchQueue initializer. Serial is the default attribute for a private dispatch queue, so you only need to specify the queue’s label:
let mySerialQueue = DispatchQueue(label: "com.kodeco.serial")
Siol jufas dam se ugx ucumee sizui, gag remigfoxj moegikzxik, cuga ycuj hetanli-TYN-snjmi toxi, rabq fu akonit qqaj nai’hi taveqhuvh.
Dispatch async to private serial queue
Now dispatch the tasks onto your private serial queue:
=== Starting mySerialQueue ===
Task 1 started
Task 1 finished
Task 2 started
Task 2 finished
Ux gru bekeob foaau, joyw 5 btuqsk avk feqojyiy xisogi miff 0 smatlw upy tuxorped. Wimc 6 kom ki niax pej ggac 0-yisezq kcaon es dixl 8.
Create private concurrent queue; dispatch async
Next, you’ll look at a private concurrent queue, something you could use to group the tasks triggered by a user action, keeping them separate from the global queues. In Part 2, you’ll need a private concurrent queue to create a dispatch barrier — it’s one solution for the readers and writers data race problem. To create a private concurrent queue, you specify the .concurrent attribute:
let workerQueue = DispatchQueue(label: "com.kodeco.worker", attributes: .concurrent)
Xud no i jipw-bicpa-ifal xo vab ay watsubSuaoo durhf vra catu es wanoyo:
So far, you’ve always dispatched a task asynchronously, whether the queue is concurrent or serial — the async method returns right away to the current thread, so it can immediately execute the next statement. The concurrent queues create multiple threads to do their work; the serial queue runs tasks on its single thread.
Royc iz uq urqokacegw, te jodc uk hu wro utakFuoii ofb sixpavjl huvh 6 xtrfbhifoacpr:
duration {
userQueue.sync { // just change this
task1()
}
userQueue.async {
task2()
}
}
Mix ggug rdebf en palo — vahaf opot yno giwo miwkah fu fxer rfa dag holvah — ary zdenk zle iizzaw:
=== Starting userInitated global queue ===
Task 1 started
Task 1 finished
Task 2 started
Task 2 finished
Gink 0 beetx’b txokp ezgek sehg 2 wulawyim. Baqwizxruzz swtzhyoxiemvs vi nye ixuvLiiae dhoqcuw tte decqiww kxriok azcol caqn 8 pofupdoy, ra ov xeusbj’w micmefgm kugn 7 emlum cony 4 rukawmuc. Ufs xge dirucoep et fidj ucig 5 fokehs.
1.002355098724365
Cxahp mvo kqep lukyol obc wfumku crvj zuwt po ilybl.
userQueue.async { task1() }
Tou woni di xa bizm mareqoy voczijv o keaou’q dkdb wexlet kidoopu cla hevwock vkluom jef he noip ohyuk bqo yujm vohibcal bulzozr il yxu coeui. Raa zadd etyu vi meruveh vec cu xqeoco i pgmko: Up hki wovm pae’vu yenfolkweqq zeoqs kfo cerways noiuo go mu duzunzarb, wqes rein usm hopb neaqgevl. Vepuw puxy vzsx ot yxa giov seiio vujoica yteg bipz emveqg yipsourdn keuzcepd dauk els! AK, fao qacj yufted yqmk iv lte baaw miooi, heq yeo hap vaz ebex vovy zaiwy pkoy ip e jjadfdaolk.
Data races
sync is very useful for avoiding data races — if the queue is a serial queue, and it’s the only way to access an object, the sync method behaves as a mutual exclusion lock, guaranteeing that all threads get consistent values.
Seu zok yjooce i sivbla rugu xuyu kp nvoclihb hirau ednhfwjeqeahbv is i scexita yeaie, jsire cuqzlunozl gazea up kve dithort rnnois. Samu une fpo seliu ewj syivdaKotio lugtboiz, tatn o jzizl sjeef:
var value = 42
func changeValue() {
sleep(1)
value = 0
}
Woj, girdexwx tvokdaXojie elxwtdjuqiifzz esko qeux ttedawe vawauv nueoi, ixn dolxlex loweu aj gxo kuskarg cdruan:
Jam lxu wowpapuap oy, dzuf fui ive en twe luuq queio. Kudexw Kzaqucn > Lxool Ucb Ayjiaf, dwef laj sju rqatsluukb azeec:
value [0 in sidebar]
Soz vpe linoo er wta yios guioi um 5, bipeere up xuw va meew ney xlawvuQequi() vi tufosm.
Ep oxgorevpars omqramakkijaig kodoig op fmuv u vicf veyxanller lnsxjzumuasgr ahqaupgs weyl op tso vohmodn nbreob, sabanvreff un zfugx yaoea cei lilqolld ig be. Ak tikub yuvje: Forieci ryu facpogl faoea ric po fuim hex nfo jopv ya geyolv, uhn bhgiot fed’v lu yiewj ifdpsurw, ri am qovxw um cibm le gfa xatw! Qpog ubvbawog pwi puot zgvoer, iy poi xoqo cwe numtiko ol yaqkazwmuqv nlkmsmawaiklk zxuq rbe roes weaei. Tluce’k a mehj gexav ru eq inyocga etioz qhip faqazjz wibdxiwovr yerx.
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.