SlideShare uma empresa Scribd logo
1 de 56
Baixar para ler offline
ASYNC
Jan Škrášek
@hrachcz
ASYNC
ASYNC JS, PHP
ASYNC JS, C#
ASYNC Kotlin
ASYNC PHP #2
ASYNC
Kolik potřebuji vláken?
Potřebuji k tomu speciální syntaxi v jazyce?
Asynchronous programming
“not existing or occurring at the same time”
Threads
https://en.wikipedia.org/wiki/Thread_(computing)
● Drahé
● Omezené
Async
thread
● Vlastnost jazyka / runtime
● Levné
● Téměř neomezené
Async callbacks
btn.setOnClickListener {
btn.text = "World"
}
btn.text = "Hello"
fetch(uri)
.then({ response ->
response.json()
})
.then({ json ->
val key = json["key"]
})
Async Callback + Promise
Async - EventLoop
while (!taskQueue.isEmpty()) {
val task = taskQueue.dequeue()
task.run()
if (!task->isFinished()) {
taskQueue.enqueue(task)
}
}
Javascript / NodeJS
NodeJS: io & cpu threads for internal functions
Javascript: WebWorkers
Image source: http://synsem.com/SyncNotAsync/
Async - syntax sugar
● CALLBACK
● PROMISE - CALLBACK
● YIELD
● ASYNC AWAIT
● SUSPEND / COROUTINES
Async Expression - YIELD
function download(): Generator {
$download = start_download();
while (true) {
yield;
if (is_download_finished($download)) {
return get_download_status($download);
}
}
}
Async Examples - YIELD
function downloadAndParse(): string {
$response = download(); // is Generator
return json_decode($response) // ???
}
Async Examples - YIELD
function downloadAndParse() {
$response = runAndGet(download());
return json_decode($response)
}
function runAndGet(Generator $generator) {
while ($gen->valid()) $gen->next();
sleep(1);
return $generator->getReturn();
}
Async Examples - YIELD
function downloadAndParse(): Generator {
$generator = download();
yield from $generator;
$response = $generator->getReturn();
return json_decode($response)
}
Async Examples - YIELD
function downloadAndParse(): Generator {
$generator = download();
$response = yield from $generator;
return json_decode($response)
}
YIELD keywords
● PHP
○ yield
○ yield from
○ Generator; getReturn()
● Javascript
○ function*
○ yield
○ yield*
○ result = yield* download();
ASYNC / AWAIT - a syntax sugar 🍬🍭🍩
async function downloadAndParse() {
$response = await download();
return json_decode($response)
}
ASYNC / AWAIT - wrapping callbacks 🍬🍭🍩
async function sleep(miliseconds) {
return new Promise(function(resolve) {
setTimeout(()=>{resolve()}, miliseconds)
});
}
(async () => {
await sleep(2000);
// do something
})()
ASYNC / AWAIT - a syntax sugar 🍬🍭🍩
- Awaitnout funkci mohu spustit pouze z jiné async funkce
nebo async scope
- Async scope:
C#: async main(), async UI events
JS: (async () => { … })() - top-level funkce co nikdy
nerejectuje; nebo pouzit API z Promise
Kotlin: async main(), coroutine launchers
ASYNC / AWAIT - C# - task it all 💻💻💻
- Async funkce vrací Task<T>
- ± Promise instance
- await rozbalí
ASYNC / AWAIT - C# - wrap a callback
public Task<HttpResponse> LoadHtmlAsync(string url)
{
var task = new TaskCompletionSource<HttpResponse>();
LoadHtml(url, result => { task.SetResult(result); });
return task.Task;
}
C#: So, we are ready to … or?
● Cancellation
● Task allocation
● Thread switching
C# ASYNC: cancellation
void Autocomplete(text: string) {
// cancel previous search task
var searchTask = SearchAsync(text);
var result = await searchTask;
// process result
}
C# ASYNC: cancellation
private CancellationTokenSource? cts = null
void Autocomplete(text: string) {
cts?.Cancel()
cts = new CancellationTokenSource();
try {
var result = await SearchAsync(text, cts.Token);
// process result
} catch (OperationCanceledException) {
} finally { cts?.Dispose() }
}
C# ASYNC: task allocation
public async Task<bool> MoveNextAsync()
{
if (_bufferedCount == 0)
{
await FillBuffer();
}
return _bufferedCount > 0;
}
C# ASYNC: task allocation
public async Task<bool> MoveNextAsync()
{
if (_bufferedCount == 0)
{
await FillBuffer();
}
return _bufferedCount > 0;
}
C# ASYNC: task allocation
public async ValueTask<bool> MoveNextAsync()
{
if (_bufferedCount == 0)
{
await FillBuffer();
}
return _bufferedCount > 0;
}
Parallel ASYNC AWAIT
- Main (UI) thread
- Jumping to different threads
C# ASYNC: thread switching
private async void button1_Click(object sender, EventArgs e
{
Button1.enabled = false;
await SynchronizeAsync();
Button1.enabled = true;
}
C# ASYNC: thread switching
C# ASYNC: thread switching
private async void button1_Click(object sender, EventArgs e
{
…
}
async Task Synchronize()
{
Task.Run(() => { … })
…
await httpRequest.executeAsync().configureAwait(false)
}
How it works - internally
https://www.markopapic.com/csharp-under-the-hood-async-await/
static async Task BarAsync()
{
Console.WriteLine("This happens before await");
int i = await QuxAsync();
Console.WriteLine("This happens after await. The result of
await is " + i);
}
static Task BarAsync()
{
Program.<BarAsync>d__2 stateMachine;
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
stateMachine.<>t__builder.Start<Program.<BarAsync>d__2>(ref
stateMachine);
return stateMachine.<>t__builder.Task;
}
private struct <BarAsync>d__2 : IAsyncStateMachine {
public int <>1__state;
public AsyncTaskMethodBuilder <>t__builder;
private TaskAwaiter<int> <>u__1;
void IAsyncStateMachine.MoveNext()
{
int num1 = this.<>1__state;
try {
TaskAwaiter<int> awaiter;
int num2;
if (num1 != 0)
{
Console.WriteLine("This happens before await");
awaiter = Program.QuxAsync().GetAwaiter();
if (num1 != 0)
{
Console.WriteLine("This happens before await");
awaiter = Program.QuxAsync().GetAwaiter();
if (!awaiter.IsCompleted){
this.<>1__state = num2 = 0;
this.<>u__1 = awaiter;
this.<>t__builder.AwaitUnsafeOnCompleted(ref await..
return;
}
}else{
awaiter = this.<>u__1;
this.<>u__1 = new TaskAwaiter<int>();
this.<>1__state = num2 = -1;
}
if (num1 != 0)
{
Console.WriteLine("This happens before await");
awaiter = Program.QuxAsync().GetAwaiter();
if (!awaiter.IsCompleted){
…
return;
}
}else{
awaiter = this.<>u__1;
this.<>u__1 = new TaskAwaiter<int>();
this.<>1__state = num2 = -1;
}
Console.WriteLine("This happens after await. The result of
await is " + (object) awaiter.GetResult());
Kotlin & Coroutines 💖
Implictní await!
Kotlin & Coroutines
suspend fun download(): HttpResponse {
}
suspend fun myFun() {
val response = download()
}
Kotlin & Coroutines
fun download(c: Continuation<HttpResponse>): HttpResponse {
}
interface Continuation<in T> {
val context: CoroutineContext
fun resume(value: T)
fun resumeWithException(exception: Throwable)
}
Kotlin & Coroutines
suspend fun search(test: String): HttpResponse {
}
private var job: Job? = null
fun autocomplete(text: String) {
job?.cancel()
job = GlobalScope.launch(Dispatchers.IO) {
val response = download(text: String)
...
}
}
Kotlin & Coroutines
fun search(test: String): Deferred<HttpResponse> {
}
private var job: Job? = null
fun autocomplete(text: String) {
job?.cancel()
job = GlobalScope.launch(Dispatchers.IO) {
val response = download(text: String).await()
...
}
}
Kotlin & Coroutines
val jobs = mutableListOf<Deferred<Int>>()
for (i in 0..1_000_000) {
jobs += GlobalScope.async(Dispatchers.Default) {
i + 1
}
}
val nums = jobs.map { it.await() }
https://pl.kotl.in/sf0502yYI
Kotlin & Coroutines
suspend fun fetchId(): Int {
return suspendCoroutine{ continuation ->
api.send(
uri,
{ continuation.resume(it) }
)
}
}
PHP
😶
PHP - async s callbacky
- Potrebuji nejaky event loop
- Tzn. nekde zacne bezet run(), ktere nekonci, dokud jsou tasky
ReactPHP
$loop = ReactEventLoopFactory::create();
$server = new ReactHttpServer(function
(ServerRequestInterface $r) {
...
return new ReactHttpResponse(...);
});
$socket = new ReactSocketServer(8080, $loop);
$server->listen($socket);
echo "Server running at http://127.0.0.1:8080n";
$loop->run();
ReactPHP
PHP a ASYNC - amphp
AmpLoop::run(function() {
$config = AmpMysqlConnectionConfig::fromString("host=
$pool = AmpMysqlpool($config);
$statement = yield $pool->prepare("SELECT * FROM table
$result = yield $statement->execute([1337]);
while (yield $result->advance()) {
$row = $result->getCurrent();
}
});
PHP a ASYNC - amphp
class Promise {
public $result = "Test";
}
function test(): Generator {
$promise = new Promise();
$result = yield $promise;
var_dump($result);
}
$gen = test();
// RUN implementation
$p1 = $gen->current();
$gen->send($p1->result);
PHP a ASYNC - amphp
function test(): Promise {
return Ampcall(function() {
$promise = new Promise();
$result = yield $promise;
var_dump($result);
});
}
Reading
https://github.com/juzna/nette-sandbox-flow/
https://nikic.github.io/2012/12/22/Cooperative-multitasking-using-coroutines-in-PH
P.html
What’s next
● RUST
● GO
● Avoid shared state - flows, RX, channels, ...
Jaké máte otázky?
Díky za pozornost!
Twitter @hrachcz
GitHub hrach

Mais conteúdo relacionado

Mais procurados

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 

Mais procurados (20)

RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Scalable Angular 2 Application Architecture
Scalable Angular 2 Application ArchitectureScalable Angular 2 Application Architecture
Scalable Angular 2 Application Architecture
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await Mistakes
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Standing the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternStanding the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider Pattern
 
Any event intro
Any event introAny event intro
Any event intro
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-es
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test
 
Correcting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NETCorrecting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NET
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
 
Будь первым
Будь первымБудь первым
Будь первым
 

Semelhante a Asynchronní programování

Orsiso
OrsisoOrsiso
Orsiso
e27
 

Semelhante a Asynchronní programování (20)

Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Async Debugging - A Practical Guide to survive !
Async Debugging - A Practical Guide to survive !Async Debugging - A Practical Guide to survive !
Async Debugging - A Practical Guide to survive !
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Orsiso
OrsisoOrsiso
Orsiso
 
20220529_UniTask_Intro.pptx
20220529_UniTask_Intro.pptx20220529_UniTask_Intro.pptx
20220529_UniTask_Intro.pptx
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Finagle - an intro to rpc & a sync programming in jvm
Finagle - an intro to rpc & a sync programming in jvmFinagle - an intro to rpc & a sync programming in jvm
Finagle - an intro to rpc & a sync programming in jvm
 

Mais de PeckaDesign.cz

Mais de PeckaDesign.cz (20)

Péhápkaři v Pecce: Naše cesta k read-modelu – Vojtěch Buba –18. 5. 2022
Péhápkaři v Pecce: Naše cesta k read-modelu – Vojtěch Buba –18. 5. 2022Péhápkaři v Pecce: Naše cesta k read-modelu – Vojtěch Buba –18. 5. 2022
Péhápkaři v Pecce: Naše cesta k read-modelu – Vojtěch Buba –18. 5. 2022
 
Péhápkaři v Pecce: Jak zrefaktorovat letitou aplikaci a zároveň začít na zele...
Péhápkaři v Pecce: Jak zrefaktorovat letitou aplikaci a zároveň začít na zele...Péhápkaři v Pecce: Jak zrefaktorovat letitou aplikaci a zároveň začít na zele...
Péhápkaři v Pecce: Jak zrefaktorovat letitou aplikaci a zároveň začít na zele...
 
WebTop100 Case study MEGAPIXEL – Redesign spuštěný proti pravidlům
WebTop100 Case study MEGAPIXEL – Redesign spuštěný proti pravidlůmWebTop100 Case study MEGAPIXEL – Redesign spuštěný proti pravidlům
WebTop100 Case study MEGAPIXEL – Redesign spuštěný proti pravidlům
 
Péhápkaři v Pecce: Sbohem PeckaCI, vítej Github Actions – Jakub Englický –27....
Péhápkaři v Pecce: Sbohem PeckaCI, vítej Github Actions – Jakub Englický –27....Péhápkaři v Pecce: Sbohem PeckaCI, vítej Github Actions – Jakub Englický –27....
Péhápkaři v Pecce: Sbohem PeckaCI, vítej Github Actions – Jakub Englický –27....
 
Péhápkaři v Pecce: Podpora PHP8 v Kdyby/Redis a Kdyby/RabbitMQ – Václav Čevel...
Péhápkaři v Pecce: Podpora PHP8 v Kdyby/Redis a Kdyby/RabbitMQ – Václav Čevel...Péhápkaři v Pecce: Podpora PHP8 v Kdyby/Redis a Kdyby/RabbitMQ – Václav Čevel...
Péhápkaři v Pecce: Podpora PHP8 v Kdyby/Redis a Kdyby/RabbitMQ – Václav Čevel...
 
Péhápkaři v Pecce: Půl roku na cestách jako digitální nomád – Jan Kadeřábek –...
Péhápkaři v Pecce: Půl roku na cestách jako digitální nomád – Jan Kadeřábek –...Péhápkaři v Pecce: Půl roku na cestách jako digitální nomád – Jan Kadeřábek –...
Péhápkaři v Pecce: Půl roku na cestách jako digitální nomád – Jan Kadeřábek –...
 
Péhápkaři v Pecce: Vývoj vlastního 'ORM' – Václav Čevela – 20. 11. 2019
Péhápkaři v Pecce: Vývoj vlastního 'ORM' – Václav Čevela – 20. 11. 2019Péhápkaři v Pecce: Vývoj vlastního 'ORM' – Václav Čevela – 20. 11. 2019
Péhápkaři v Pecce: Vývoj vlastního 'ORM' – Václav Čevela – 20. 11. 2019
 
Tvorba nových vstupních stránek z pohledu SEO
Tvorba nových vstupních stránek z pohledu SEO Tvorba nových vstupních stránek z pohledu SEO
Tvorba nových vstupních stránek z pohledu SEO
 
Péhápkaři v Pecce: pd/forms – Petr Klobás – 16. 10. 2019
Péhápkaři v Pecce: pd/forms – Petr Klobás – 16. 10. 2019Péhápkaři v Pecce: pd/forms – Petr Klobás – 16. 10. 2019
Péhápkaři v Pecce: pd/forms – Petr Klobás – 16. 10. 2019
 
Péhápkaři v Pecce: Za hranicemi DateTime – Jiří Pudil – 16. 10. 2019
Péhápkaři v Pecce: Za hranicemi DateTime – Jiří Pudil – 16. 10. 2019Péhápkaři v Pecce: Za hranicemi DateTime – Jiří Pudil – 16. 10. 2019
Péhápkaři v Pecce: Za hranicemi DateTime – Jiří Pudil – 16. 10. 2019
 
Péhápkaři v Pecce: Úvod do monitoringu – Tomáš Kozák – 16. 10. 2019
Péhápkaři v Pecce: Úvod do monitoringu – Tomáš Kozák – 16. 10. 2019Péhápkaři v Pecce: Úvod do monitoringu – Tomáš Kozák – 16. 10. 2019
Péhápkaři v Pecce: Úvod do monitoringu – Tomáš Kozák – 16. 10. 2019
 
ElasticSearch Dump
ElasticSearch DumpElasticSearch Dump
ElasticSearch Dump
 
Pokročilá validace síly hesla
Pokročilá validace síly heslaPokročilá validace síly hesla
Pokročilá validace síly hesla
 
Péhápkaři v Pecce: Každodenní problémy s implementací Facebook Api – Marek Hu...
Péhápkaři v Pecce: Každodenní problémy s implementací Facebook Api – Marek Hu...Péhápkaři v Pecce: Každodenní problémy s implementací Facebook Api – Marek Hu...
Péhápkaři v Pecce: Každodenní problémy s implementací Facebook Api – Marek Hu...
 
Péhápkaři v Pecce: Čtyři hlavní příčiny dysfunkčních návyků v týmu – Michal A...
Péhápkaři v Pecce: Čtyři hlavní příčiny dysfunkčních návyků v týmu – Michal A...Péhápkaři v Pecce: Čtyři hlavní příčiny dysfunkčních návyků v týmu – Michal A...
Péhápkaři v Pecce: Čtyři hlavní příčiny dysfunkčních návyků v týmu – Michal A...
 
Péhápkaři v Pecce: Jak si lokálně spustit Travis CI Build – Jakub Englický – ...
Péhápkaři v Pecce: Jak si lokálně spustit Travis CI Build – Jakub Englický – ...Péhápkaři v Pecce: Jak si lokálně spustit Travis CI Build – Jakub Englický – ...
Péhápkaři v Pecce: Jak si lokálně spustit Travis CI Build – Jakub Englický – ...
 
Péhápkaři v Pecce: Jak jsme neposlali pull request do PHP – Milan Pála – 17. ...
Péhápkaři v Pecce: Jak jsme neposlali pull request do PHP – Milan Pála – 17. ...Péhápkaři v Pecce: Jak jsme neposlali pull request do PHP – Milan Pála – 17. ...
Péhápkaři v Pecce: Jak jsme neposlali pull request do PHP – Milan Pála – 17. ...
 
Péhápkaři v Pecce: Zend Expressive: PSR framework který vás dostane – Jan Kad...
Péhápkaři v Pecce: Zend Expressive: PSR framework který vás dostane – Jan Kad...Péhápkaři v Pecce: Zend Expressive: PSR framework který vás dostane – Jan Kad...
Péhápkaři v Pecce: Zend Expressive: PSR framework který vás dostane – Jan Kad...
 
Péhápkaři v Pecce: Jak na bezpečnostní hlavičky – Marek Humpolík – 23. 1. 2019
Péhápkaři v Pecce: Jak na bezpečnostní hlavičky – Marek Humpolík – 23. 1. 2019Péhápkaři v Pecce: Jak na bezpečnostní hlavičky – Marek Humpolík – 23. 1. 2019
Péhápkaři v Pecce: Jak na bezpečnostní hlavičky – Marek Humpolík – 23. 1. 2019
 
PeckaAcademy - Zbožové srovnávače od A-Z - Petra Mariánková
PeckaAcademy - Zbožové srovnávače od A-Z - Petra MariánkováPeckaAcademy - Zbožové srovnávače od A-Z - Petra Mariánková
PeckaAcademy - Zbožové srovnávače od A-Z - Petra Mariánková
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 

Asynchronní programování

  • 2. ASYNC ASYNC JS, PHP ASYNC JS, C# ASYNC Kotlin ASYNC PHP #2
  • 3. ASYNC Kolik potřebuji vláken? Potřebuji k tomu speciální syntaxi v jazyce?
  • 4. Asynchronous programming “not existing or occurring at the same time”
  • 6. Async thread ● Vlastnost jazyka / runtime ● Levné ● Téměř neomezené
  • 7. Async callbacks btn.setOnClickListener { btn.text = "World" } btn.text = "Hello"
  • 8. fetch(uri) .then({ response -> response.json() }) .then({ json -> val key = json["key"] }) Async Callback + Promise
  • 9. Async - EventLoop while (!taskQueue.isEmpty()) { val task = taskQueue.dequeue() task.run() if (!task->isFinished()) { taskQueue.enqueue(task) } }
  • 10. Javascript / NodeJS NodeJS: io & cpu threads for internal functions Javascript: WebWorkers Image source: http://synsem.com/SyncNotAsync/
  • 11. Async - syntax sugar ● CALLBACK ● PROMISE - CALLBACK ● YIELD ● ASYNC AWAIT ● SUSPEND / COROUTINES
  • 12. Async Expression - YIELD function download(): Generator { $download = start_download(); while (true) { yield; if (is_download_finished($download)) { return get_download_status($download); } } }
  • 13. Async Examples - YIELD function downloadAndParse(): string { $response = download(); // is Generator return json_decode($response) // ??? }
  • 14. Async Examples - YIELD function downloadAndParse() { $response = runAndGet(download()); return json_decode($response) } function runAndGet(Generator $generator) { while ($gen->valid()) $gen->next(); sleep(1); return $generator->getReturn(); }
  • 15. Async Examples - YIELD function downloadAndParse(): Generator { $generator = download(); yield from $generator; $response = $generator->getReturn(); return json_decode($response) }
  • 16. Async Examples - YIELD function downloadAndParse(): Generator { $generator = download(); $response = yield from $generator; return json_decode($response) }
  • 17. YIELD keywords ● PHP ○ yield ○ yield from ○ Generator; getReturn() ● Javascript ○ function* ○ yield ○ yield* ○ result = yield* download();
  • 18. ASYNC / AWAIT - a syntax sugar 🍬🍭🍩 async function downloadAndParse() { $response = await download(); return json_decode($response) }
  • 19. ASYNC / AWAIT - wrapping callbacks 🍬🍭🍩 async function sleep(miliseconds) { return new Promise(function(resolve) { setTimeout(()=>{resolve()}, miliseconds) }); } (async () => { await sleep(2000); // do something })()
  • 20. ASYNC / AWAIT - a syntax sugar 🍬🍭🍩 - Awaitnout funkci mohu spustit pouze z jiné async funkce nebo async scope - Async scope: C#: async main(), async UI events JS: (async () => { … })() - top-level funkce co nikdy nerejectuje; nebo pouzit API z Promise Kotlin: async main(), coroutine launchers
  • 21. ASYNC / AWAIT - C# - task it all 💻💻💻 - Async funkce vrací Task<T> - ± Promise instance - await rozbalí
  • 22. ASYNC / AWAIT - C# - wrap a callback public Task<HttpResponse> LoadHtmlAsync(string url) { var task = new TaskCompletionSource<HttpResponse>(); LoadHtml(url, result => { task.SetResult(result); }); return task.Task; }
  • 23. C#: So, we are ready to … or? ● Cancellation ● Task allocation ● Thread switching
  • 24. C# ASYNC: cancellation void Autocomplete(text: string) { // cancel previous search task var searchTask = SearchAsync(text); var result = await searchTask; // process result }
  • 25. C# ASYNC: cancellation private CancellationTokenSource? cts = null void Autocomplete(text: string) { cts?.Cancel() cts = new CancellationTokenSource(); try { var result = await SearchAsync(text, cts.Token); // process result } catch (OperationCanceledException) { } finally { cts?.Dispose() } }
  • 26. C# ASYNC: task allocation public async Task<bool> MoveNextAsync() { if (_bufferedCount == 0) { await FillBuffer(); } return _bufferedCount > 0; }
  • 27. C# ASYNC: task allocation public async Task<bool> MoveNextAsync() { if (_bufferedCount == 0) { await FillBuffer(); } return _bufferedCount > 0; }
  • 28. C# ASYNC: task allocation public async ValueTask<bool> MoveNextAsync() { if (_bufferedCount == 0) { await FillBuffer(); } return _bufferedCount > 0; }
  • 29. Parallel ASYNC AWAIT - Main (UI) thread - Jumping to different threads
  • 30. C# ASYNC: thread switching private async void button1_Click(object sender, EventArgs e { Button1.enabled = false; await SynchronizeAsync(); Button1.enabled = true; }
  • 31. C# ASYNC: thread switching
  • 32. C# ASYNC: thread switching private async void button1_Click(object sender, EventArgs e { … } async Task Synchronize() { Task.Run(() => { … }) … await httpRequest.executeAsync().configureAwait(false) }
  • 33. How it works - internally https://www.markopapic.com/csharp-under-the-hood-async-await/
  • 34. static async Task BarAsync() { Console.WriteLine("This happens before await"); int i = await QuxAsync(); Console.WriteLine("This happens after await. The result of await is " + i); }
  • 35. static Task BarAsync() { Program.<BarAsync>d__2 stateMachine; stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create(); stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start<Program.<BarAsync>d__2>(ref stateMachine); return stateMachine.<>t__builder.Task; }
  • 36. private struct <BarAsync>d__2 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; private TaskAwaiter<int> <>u__1; void IAsyncStateMachine.MoveNext() { int num1 = this.<>1__state; try { TaskAwaiter<int> awaiter; int num2; if (num1 != 0) { Console.WriteLine("This happens before await"); awaiter = Program.QuxAsync().GetAwaiter();
  • 37. if (num1 != 0) { Console.WriteLine("This happens before await"); awaiter = Program.QuxAsync().GetAwaiter(); if (!awaiter.IsCompleted){ this.<>1__state = num2 = 0; this.<>u__1 = awaiter; this.<>t__builder.AwaitUnsafeOnCompleted(ref await.. return; } }else{ awaiter = this.<>u__1; this.<>u__1 = new TaskAwaiter<int>(); this.<>1__state = num2 = -1; }
  • 38. if (num1 != 0) { Console.WriteLine("This happens before await"); awaiter = Program.QuxAsync().GetAwaiter(); if (!awaiter.IsCompleted){ … return; } }else{ awaiter = this.<>u__1; this.<>u__1 = new TaskAwaiter<int>(); this.<>1__state = num2 = -1; } Console.WriteLine("This happens after await. The result of await is " + (object) awaiter.GetResult());
  • 39. Kotlin & Coroutines 💖 Implictní await!
  • 40. Kotlin & Coroutines suspend fun download(): HttpResponse { } suspend fun myFun() { val response = download() }
  • 41. Kotlin & Coroutines fun download(c: Continuation<HttpResponse>): HttpResponse { } interface Continuation<in T> { val context: CoroutineContext fun resume(value: T) fun resumeWithException(exception: Throwable) }
  • 42. Kotlin & Coroutines suspend fun search(test: String): HttpResponse { } private var job: Job? = null fun autocomplete(text: String) { job?.cancel() job = GlobalScope.launch(Dispatchers.IO) { val response = download(text: String) ... } }
  • 43. Kotlin & Coroutines fun search(test: String): Deferred<HttpResponse> { } private var job: Job? = null fun autocomplete(text: String) { job?.cancel() job = GlobalScope.launch(Dispatchers.IO) { val response = download(text: String).await() ... } }
  • 44. Kotlin & Coroutines val jobs = mutableListOf<Deferred<Int>>() for (i in 0..1_000_000) { jobs += GlobalScope.async(Dispatchers.Default) { i + 1 } } val nums = jobs.map { it.await() } https://pl.kotl.in/sf0502yYI
  • 45. Kotlin & Coroutines suspend fun fetchId(): Int { return suspendCoroutine{ continuation -> api.send( uri, { continuation.resume(it) } ) } }
  • 47. PHP - async s callbacky - Potrebuji nejaky event loop - Tzn. nekde zacne bezet run(), ktere nekonci, dokud jsou tasky
  • 48. ReactPHP $loop = ReactEventLoopFactory::create(); $server = new ReactHttpServer(function (ServerRequestInterface $r) { ... return new ReactHttpResponse(...); }); $socket = new ReactSocketServer(8080, $loop); $server->listen($socket); echo "Server running at http://127.0.0.1:8080n"; $loop->run();
  • 50. PHP a ASYNC - amphp AmpLoop::run(function() { $config = AmpMysqlConnectionConfig::fromString("host= $pool = AmpMysqlpool($config); $statement = yield $pool->prepare("SELECT * FROM table $result = yield $statement->execute([1337]); while (yield $result->advance()) { $row = $result->getCurrent(); } });
  • 51. PHP a ASYNC - amphp class Promise { public $result = "Test"; } function test(): Generator { $promise = new Promise(); $result = yield $promise; var_dump($result); } $gen = test(); // RUN implementation $p1 = $gen->current(); $gen->send($p1->result);
  • 52. PHP a ASYNC - amphp function test(): Promise { return Ampcall(function() { $promise = new Promise(); $result = yield $promise; var_dump($result); }); }
  • 54. What’s next ● RUST ● GO ● Avoid shared state - flows, RX, channels, ...
  • 56. Díky za pozornost! Twitter @hrachcz GitHub hrach