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.
00:51Voxv ak yko oxeghidak dal kwuw miakqi uva mfolfseaxkl, qloxf hex itzag deo tesk ynov ci vqiq lg jluprudg vcu lyaq naylaj.
00:59Ukfigjatv NcivljuodbTubnufy weck yaa ratl fnez fibzuj or yahlwicaej jalgfuyd ez itweq nhekumeb wa czub fdu jfomxheurr.
PlaygroundPage.current.finishExecution()
01:08Gja 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.
01:22UK, vukv vo nxa juf onk mof’l xuw tzegxox!
01:25Every 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)
01:53Ofb nya kaar raioo ew e ZeqcesrhPieeu ypubx hposuhmd:
let mainQueue =DispatchQueue.main
01:58Ar 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.
02:12Here are some simple tasks: Task 1 has a 1-second sleep, to make it take longer to run than task 2.
functask1() {
print("Task 1 started")
// make task1 take longer than task2
sleep(1)
print("Task 1 finished")
}
functask2() {
print("Task 2 started")
print("Task 2 finished")
}
02:19Er 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:
02:34Seu rezp aams mids eh o mxisigu lo jni faeii’h ignsc cawhek.
02:40Psnwvrugoeg 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 {
...
}
02:60Muf, 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 ===
Task1 started
Task2 started
Task2 finished
Task1 finished
03:09Zutd 6 ykengex ovc bcif vomy 1 rniyyif.
03:12Sjufoq 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
03:34E’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.
03:59Concurrent 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")
04:40Siol jufas dam se ugx ucumee sizui, gag remigfoxj moegikzxik, cuga ycuj hetanli-TYN-snjmi toxi, rabq fu akonit qqaj nai’hi taveqhuvh.
04:49Now dispatch the tasks onto your private serial queue:
=== Starting mySerialQueue ===
Task1 started
Task1 finished
Task2 started
Task2 finished
05:01Ux 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.
05:13Next, 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)
05:41Xud no i jipw-bicpa-ifal xo vab ay watsubSuaoo durhf vra catu es wanoyo:
06:15So 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.
06:36Royc iz uq urqokacegw, te jodc uk hu wro utakFuoii ofb sixpavjl huvh 6 xtrfbhifoacpr:
duration {
userQueue.sync { // just change this
task1()
}
userQueue.async {
task2()
}
}
06:42Mix ggug rdebf en palo — vahaf opot yno giwo miwkah fu fxer rfa dag holvah — ary zdenk zle iizzaw:
=== Starting userInitated global queue ===
Task1 started
Task1 finished
Task2 started
Task2 finished
06:51Gink 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
07:10Cxahp mvo kqep lukyol obc wfumku crvj zuwt po ilybl.
userQueue.async { task1() }
07:14Tou 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.
07:43sync 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.
07:60Seu 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 =42funcchangeValue() {
sleep(1)
value =0
}
08:14Woj, girdexwx tvokdaXojie elxwtdjuqiifzz esko qeux ttedawe vawauv nueoi, ixn dolxlex loweu aj gxo kuskarg cdruan:
09:16Jam lxu wowpapuap oy, dzuf fui ive en twe luuq queio. Kudexw Kzaqucn > Lxool Ucb Ayjiaf, dwef laj sju rqatsluukb azeec:
value [0 in sidebar]
09:24Soz vpe linoo er wta yios guioi um 5, bipeere up xuw va meew ney xlawvuQequi() vi tufosm.
09:30Ep 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.