SlideShare a Scribd company logo
Async and Parallel Programming in F#Matthew PodwysockiSenior Consultanthttp://codebetter.com/@mattpodwysocki
AgendaF# in 15 MinutesWhy is concurrent programming so hard?What can F# do to help?
...a functional, object-oriented, imperative and explorative programming language for .NET with influences from OCaml, C#, Haskell and ErlangHi! I’m F#
Async and Parallel F#
F# in 15 Minutes – The FactsF# is a general purpose .NETlanguageF# is a multi-paradigm languageF# is a statically-typed language
F# in 15 Minutes - The Syntaxbinding names to valuesletlets = "Hello World"let (x, y) = (45, 54)let answer = x + ylet numbers = [1 .. 10]let odds = [1; 3; 5; 7; 9]let square x = x * xlet squareOf4 = square 4
F# in 15 Minutes - The Syntaxfunctions as valuesfunlet square x = x * xlet squares = List.map (fun x -> x * x) [1..10]let squares = List.map square [1..10]Operators are functions too!
F# in 15 Minutes – The Syntax|>bringing order to chaoslet (|>) x f = f xletsumOfSquares =   List.sum (List.map square [1..10])letsumOfSquares = [1..10]                    |> List.map square                   |> List.sum<|>><<See also:
F# in 15 Minutes – The Syntaxdiscriminated unionstypetype Suit = | Spade | Heart | Club | Diamondtype Rank = | Ace | King | Queen | Jack            | Value ofinttype Card = Card of Suit * RankMicrosoft Confidential
F# in 15 Minutes – The Syntaxpattern matchingmatchletcardValue (Card(s,r)) =match r with  | Ace                 -> 11  | King | Queen | Jack -> 10  | Value(x)            -> xlet (x, y) = ("x", "y")let [a; b] = [1 ; 2]Microsoft Confidential
Concurrent programmingwith shared state…Is really hard!Microsoft Confidential
Shared State Gives Us…Race conditions!Obscure error messages!Late night debugging!Locks, mutexes and semaphores, oh my!Microsoft Confidential
How Can F# Help Us?GranularityPurityImmutabilityLibraries
In Praise of ImmutabilityImmutable objects... can be relied upon... can transfer between threads... can be aliased safely... lead to (different) optimization opportunities
There is no silver bullet
Concurrency StylesAsynchronous ProgrammingParallel ProgrammingDataTaskActor Model Concurrency
Asynchronous Programming
publicstaticvoidProcessImagesInBulk(){Console.WriteLine("Processing images...  ");long t0 = Environment.TickCount;NumImagesToFinish = numImages;AsyncCallbackreadImageCallback = newAsyncCallback(ReadInImageCallback);for (inti = 0; i < numImages; i++)  {ImageStateObject state = newImageStateObject();state.pixels = newbyte[numPixels];state.imageNum = i;FileStreamfs = newFileStream(ImageBaseName + i + ".tmp",FileMode.Open, FileAccess.Read, FileShare.Read, 1, true);state.fs = fs;fs.BeginRead(state.pixels, 0, numPixels, readImageCallback,        state);  }boolmustBlock = false;lock (NumImagesMutex)  {if (NumImagesToFinish > 0)mustBlock = true;  }if (mustBlock)  {Console.WriteLine("All worker threads are queued. " +" Blocking until they complete. numLeft: {0}",NumImagesToFinish);Monitor.Enter(WaitObject);Monitor.Wait(WaitObject);Monitor.Exit(WaitObject);  }long t1 = Environment.TickCount;Console.WriteLine("Total time processing images: {0}ms",      (t1 - t0));}publicstaticvoidReadInImageCallback(IAsyncResultasyncResult){ImageStateObject state = (ImageStateObject)asyncResult.AsyncState;Streamstream = state.fs;intbytesRead = stream.EndRead(asyncResult);if (bytesRead != numPixels)thrownewException(String.Format        ("In ReadInImageCallback, got the wrong number of " +"bytes from the image: {0}.", bytesRead));ProcessImage(state.pixels, state.imageNum);stream.Close();FileStreamfs = newFileStream(ImageBaseName + state.imageNum +".done", FileMode.Create, FileAccess.Write, FileShare.None,      4096, false);fs.Write(state.pixels, 0, numPixels);fs.Close();state.pixels = null;fs = null;lock (NumImagesMutex)  {NumImagesToFinish--;if (NumImagesToFinish == 0)    {Monitor.Enter(WaitObject);Monitor.Pulse(WaitObject);Monitor.Exit(WaitObject);    }  }}using System;using System.IO;usingSystem.Threading;usingSystem.Runtime.InteropServices;usingSystem.Runtime.Remoting.Messaging;usingSystem.Security.Permissions;publicclassBulkImageProcAsync{publicconstStringImageBaseName = "tmpImage-";publicconstintnumImages = 200;publicconstintnumPixels = 512 * 512;publicstaticintprocessImageRepeats = 20;publicstaticintNumImagesToFinish = numImages;publicstaticObject[] NumImagesMutex = newObject[0];publicstaticObject[] WaitObject = newObject[0];publicclassImageStateObject  {publicbyte[] pixels;publicintimageNum;publicFileStreamfs;  }“Asynchronous File I/O”http://msdn.microsoft.com/en-us/library/kztecsys.aspxState of Asynchronous I/O
letProcessImageAsynci =async { useinStream = File.OpenRead(sprintf"Image%d.tmp"i)let! pixels = inStream.AsyncRead(numPixels)let pixels' = ProcessImage(pixels, i)useoutStream = File.OpenWrite(sprintf"Image%d.done"i)do!outStream.AsyncWrite(pixels') }letProcessImagesAsync() =let tasks = [ foriin 1..numImages ->ProcessImageAsync(i) ]letparallelTasks = Async.Parallel tasksAsync.RunSynchronouslyparallelTasksWhy Isn’t it This Easy?
Read streamasynchronouslyletProcessImageAsynci =async { useinStream = File.OpenRead(sprintf"Image%d.tmp"i)let! pixels = inStream.AsyncRead(numPixels)let pixels' = ProcessImage(pixels, i)useoutStream = File.OpenWrite(sprintf"Image%d.done"i)do!outStream.AsyncWrite(pixels') }letProcessImagesAsync() =let tasks = [ for i in 1..numImages ->ProcessImageAsynci ]letparallelTasks = Async.Parallel tasksAsync.RunSynnchronouslyparallelTasksThis object coordinatesWrite stream asynchronouslyGenerate the tasks and queue them in parallel“!” = “asynchronous”Digging Deeper…
letgetHtml (url:string) =async { let request = WebRequest.Createurluse! response = request.AsyncGetResponse()use stream = response.GetResponseStream()use reader = newStreamReader(stream)return! reader.AsyncReadToEnd() }What we’re really writingletgetHtml (url:string) =async.Delay(fun () ->let request = WebRequest.Createurlasync.Bind(request.AsyncGetResponse(), funresponse ->async.Using(response, fun response ->async.Using(response.GetResponseStream(), fun stream ->async.Using(new StreamReader(stream), fun reader ->reader.AsyncReadToEnd())))))
How does it work?Success ContinuationAsync<T>Execution RequestException ContinuationCancellation Continuation
Anatomy of an Async OperationAsync operationsBegin/EndtypeSystem.Net.WebRequestwithmemberthis.AsyncGetRequestStream() =Async.BuildPrimitive(this.BeginGetRequestStream, this.EndGetRequestStream)
What Do We Get For Free?Code that makes senseException propagationCancellation checkingSimple resource lifetime management
Twitter Example
Parallel ProgrammingTask ParallelData Parallel
Data Parallel ProgrammingPLINQEnable F# developers to leverage parallel hardwareAbstracts away parallelism detailsPartitions and merges data intelligentlyWorks on any seq<'a>/IEnumerable<T>let q = ratings  |> PSeq.adapt  |> PSeq.filter(funp ->p.Name = movieName &&p.Rating >= 3.0 &&p.Rating <= 5.0)  |> PSeq.sortBy(fun p ->p.Rating)  |> PSeq.map(funp ->p.CustomerId)
Task Parallel ProgrammingEnable F# developers to create tasks in parallelletcomputeHash path algorithm =async { use stream = File.OpenRead pathlet! bytes = stream.AsyncRead(intstream.Length)let crypt = HashAlgorithm.Create algorithmreturncrypt.ComputeHash bytes }let algorithms = ["MD5";"SHA1";"SHA256";"SHA384";"SHA512"]let [|md5;sha1;sha256;sha384;sha512|] =Async.RunSynchronously(Async.Parallel     [for algorithm in algorithms ->computeHash path algorithm])
Task Parallel + Async WorkflowsTPL Tasks integrated in .NET 4.0 Async WorkflowsIntegrate with pre-defined tasksCalculate FuturesletgetStreamData (uri:string) =async { let request = WebRequest.Createuriuse! response = request.AsyncGetResponse()return [use stream = response.GetResponseStream()use reader = new StreamReader(stream)while not reader.EndOfStreamdoyieldreader.ReadLine()] }let result = Async.CreateAsTask <| getStreamDatamyUrido result.Start()letresultValue = result.Value
Bing Translator Example
Actor Model ConcurrencyLots of little tasksEach process does one taskAnt ColonyAnts are processes sending messages to each other
Actor Model in Action…let (<--) (m:'aMailboxProcessor) msg = m.Post(msg)typePinger = PongtypePonger = Ping ofMailboxProcessor<Pinger> | Stopletponger = newMailboxProcessor<Ponger>(funinbox ->let rec loop pongCount =async { let! msg = inbox.Receive()matchmsgwith              | Ping outbox ->                  outbox <-- Pongreturn! loop(pongCount + 1)              | Stop -> return () }    loop 0)
Actor Model in Action…letpinger count pong =  newMailboxProcessor<Pinger>(funinbox ->    let rec sendPing() =       async { pong <-- Ping(inbox)              return! loop (count - 1) }    and loop pingsLeft =      async { let! msg = inbox.Receive()              matchmsgwith              | Pong ->                  ifpingsLeft > 0 then                    pong <-- Ping(inbox)                    return! loop(pingsLeft - 1)                  else                                       pong <-- Stop                    return () }    sendPing())
Web Crawling Example
Ant Colony Example
High Performance ComputingMPI.NETDryad/DryadLINQ
What’s in Store for 2010?
Ways to Learn F#http://www.fsharp.netF# Interactive (FSI)Language SpecificationF# Team BlogsF# (FSharp) Discussion DLhttp://cs.hubfs.netCodePlex F# Samples.NET ReflectorGo to Definition
Books about F#
Resources - BlogsDon Symehttp://blogs.msdn.com/dsyme/Luke Hobanhttp://blogs.msdn.com/lukeh/Brian McNamarahttp://lorgonblog.spaces.live.com/Chris Smithhttp://blogs.msdn.com/chrsmith/Jomo Fisherhttp://blogs.msdn.com/jomo_fisher/Planet F#http://feeds.feedburner.com/planet_fsharp

More Related Content

What's hot (19)

Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
Slawomir Dorzak
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
Wei-Ning Huang
 
Command line arguments that make you smile
Command line arguments that make you smileCommand line arguments that make you smile
Command line arguments that make you smile
Martin Melin
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
Lin Yo-An
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
Phillip Trelford
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
extremecoders
 
Command Line Arguments with Getopt::Long
Command Line Arguments with Getopt::LongCommand Line Arguments with Getopt::Long
Command Line Arguments with Getopt::Long
Ian Kluft
 
Happy Go Programming Part 1
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
Lin Yo-An
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
go-lang
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
Amos Wenger
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
Tomas Petricek
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
Jimmy Schementi
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOF
Dror Bereznitsky
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
Stefan
 
Boost Maintainability
Boost MaintainabilityBoost Maintainability
Boost Maintainability
Mosky Liu
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
Mosky Liu
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
Slawomir Dorzak
 
Command line arguments that make you smile
Command line arguments that make you smileCommand line arguments that make you smile
Command line arguments that make you smile
Martin Melin
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
Lin Yo-An
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
Phillip Trelford
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
extremecoders
 
Command Line Arguments with Getopt::Long
Command Line Arguments with Getopt::LongCommand Line Arguments with Getopt::Long
Command Line Arguments with Getopt::Long
Ian Kluft
 
Happy Go Programming Part 1
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
Lin Yo-An
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
go-lang
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
Amos Wenger
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
Tomas Petricek
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
Jimmy Schementi
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOF
Dror Bereznitsky
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
Stefan
 
Boost Maintainability
Boost MaintainabilityBoost Maintainability
Boost Maintainability
Mosky Liu
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
Mosky Liu
 

Similar to Async and Parallel F# (20)

Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
Marwan Osman
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)
James Titcumb
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
Node.js
Node.jsNode.js
Node.js
Mat Schaffer
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
dantleech
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
UNO based ODF Toolkit API
UNO based ODF Toolkit APIUNO based ODF Toolkit API
UNO based ODF Toolkit API
Alexandro Colorado
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Intro to JavaFX & Widget FX
Intro to JavaFX & Widget FXIntro to JavaFX & Widget FX
Intro to JavaFX & Widget FX
Stephen Chin
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
The ten commandments for an Agile Developer
The ten commandments for an Agile DeveloperThe ten commandments for an Agile Developer
The ten commandments for an Agile Developer
Sowmya Karmali
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
Vivekanandhan Vijayan
 
F# and the DLR
F# and the DLRF# and the DLR
F# and the DLR
Richard Minerich
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
Lettering js
Lettering jsLettering js
Lettering js
davatron5000
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
JoshCasas1
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
Marwan Osman
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)
James Titcumb
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
dantleech
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Intro to JavaFX & Widget FX
Intro to JavaFX & Widget FXIntro to JavaFX & Widget FX
Intro to JavaFX & Widget FX
Stephen Chin
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
The ten commandments for an Agile Developer
The ten commandments for an Agile DeveloperThe ten commandments for an Agile Developer
The ten commandments for an Agile Developer
Sowmya Karmali
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
JoshCasas1
 

Recently uploaded (20)

UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ..."AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
Fwdays
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptxBreak Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Mohammad Jomaa
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCPMCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
Sambhav Kothari
 
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptxFrom Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
Mohammad Jomaa
 
Fully Open-Source Private Clouds: Freedom, Security, and Control
Fully Open-Source Private Clouds: Freedom, Security, and ControlFully Open-Source Private Clouds: Freedom, Security, and Control
Fully Open-Source Private Clouds: Freedom, Security, and Control
ShapeBlue
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
cloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mitacloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mita
siyaldhande02
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Introducing Ensemble Cloudlet vRouter
Introducing Ensemble  Cloudlet vRouterIntroducing Ensemble  Cloudlet vRouter
Introducing Ensemble Cloudlet vRouter
Adtran
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ..."AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
Fwdays
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptxBreak Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Break Down of Service Mesh Concepts and Implementation in AWS EKS.pptx
Mohammad Jomaa
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCPMCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
Sambhav Kothari
 
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptxFrom Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
Mohammad Jomaa
 
Fully Open-Source Private Clouds: Freedom, Security, and Control
Fully Open-Source Private Clouds: Freedom, Security, and ControlFully Open-Source Private Clouds: Freedom, Security, and Control
Fully Open-Source Private Clouds: Freedom, Security, and Control
ShapeBlue
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
cloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mitacloudgenesis cloud workshop , gdg on campus mita
cloudgenesis cloud workshop , gdg on campus mita
siyaldhande02
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Introducing Ensemble Cloudlet vRouter
Introducing Ensemble  Cloudlet vRouterIntroducing Ensemble  Cloudlet vRouter
Introducing Ensemble Cloudlet vRouter
Adtran
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 

Async and Parallel F#

  • 1. Async and Parallel Programming in F#Matthew PodwysockiSenior Consultanthttp://codebetter.com/@mattpodwysocki
  • 2. AgendaF# in 15 MinutesWhy is concurrent programming so hard?What can F# do to help?
  • 3. ...a functional, object-oriented, imperative and explorative programming language for .NET with influences from OCaml, C#, Haskell and ErlangHi! I’m F#
  • 5. F# in 15 Minutes – The FactsF# is a general purpose .NETlanguageF# is a multi-paradigm languageF# is a statically-typed language
  • 6. F# in 15 Minutes - The Syntaxbinding names to valuesletlets = "Hello World"let (x, y) = (45, 54)let answer = x + ylet numbers = [1 .. 10]let odds = [1; 3; 5; 7; 9]let square x = x * xlet squareOf4 = square 4
  • 7. F# in 15 Minutes - The Syntaxfunctions as valuesfunlet square x = x * xlet squares = List.map (fun x -> x * x) [1..10]let squares = List.map square [1..10]Operators are functions too!
  • 8. F# in 15 Minutes – The Syntax|>bringing order to chaoslet (|>) x f = f xletsumOfSquares = List.sum (List.map square [1..10])letsumOfSquares = [1..10] |> List.map square |> List.sum<|>><<See also:
  • 9. F# in 15 Minutes – The Syntaxdiscriminated unionstypetype Suit = | Spade | Heart | Club | Diamondtype Rank = | Ace | King | Queen | Jack | Value ofinttype Card = Card of Suit * RankMicrosoft Confidential
  • 10. F# in 15 Minutes – The Syntaxpattern matchingmatchletcardValue (Card(s,r)) =match r with | Ace -> 11 | King | Queen | Jack -> 10 | Value(x) -> xlet (x, y) = ("x", "y")let [a; b] = [1 ; 2]Microsoft Confidential
  • 11. Concurrent programmingwith shared state…Is really hard!Microsoft Confidential
  • 12. Shared State Gives Us…Race conditions!Obscure error messages!Late night debugging!Locks, mutexes and semaphores, oh my!Microsoft Confidential
  • 13. How Can F# Help Us?GranularityPurityImmutabilityLibraries
  • 14. In Praise of ImmutabilityImmutable objects... can be relied upon... can transfer between threads... can be aliased safely... lead to (different) optimization opportunities
  • 15. There is no silver bullet
  • 16. Concurrency StylesAsynchronous ProgrammingParallel ProgrammingDataTaskActor Model Concurrency
  • 18. publicstaticvoidProcessImagesInBulk(){Console.WriteLine("Processing images... ");long t0 = Environment.TickCount;NumImagesToFinish = numImages;AsyncCallbackreadImageCallback = newAsyncCallback(ReadInImageCallback);for (inti = 0; i < numImages; i++) {ImageStateObject state = newImageStateObject();state.pixels = newbyte[numPixels];state.imageNum = i;FileStreamfs = newFileStream(ImageBaseName + i + ".tmp",FileMode.Open, FileAccess.Read, FileShare.Read, 1, true);state.fs = fs;fs.BeginRead(state.pixels, 0, numPixels, readImageCallback, state); }boolmustBlock = false;lock (NumImagesMutex) {if (NumImagesToFinish > 0)mustBlock = true; }if (mustBlock) {Console.WriteLine("All worker threads are queued. " +" Blocking until they complete. numLeft: {0}",NumImagesToFinish);Monitor.Enter(WaitObject);Monitor.Wait(WaitObject);Monitor.Exit(WaitObject); }long t1 = Environment.TickCount;Console.WriteLine("Total time processing images: {0}ms", (t1 - t0));}publicstaticvoidReadInImageCallback(IAsyncResultasyncResult){ImageStateObject state = (ImageStateObject)asyncResult.AsyncState;Streamstream = state.fs;intbytesRead = stream.EndRead(asyncResult);if (bytesRead != numPixels)thrownewException(String.Format ("In ReadInImageCallback, got the wrong number of " +"bytes from the image: {0}.", bytesRead));ProcessImage(state.pixels, state.imageNum);stream.Close();FileStreamfs = newFileStream(ImageBaseName + state.imageNum +".done", FileMode.Create, FileAccess.Write, FileShare.None, 4096, false);fs.Write(state.pixels, 0, numPixels);fs.Close();state.pixels = null;fs = null;lock (NumImagesMutex) {NumImagesToFinish--;if (NumImagesToFinish == 0) {Monitor.Enter(WaitObject);Monitor.Pulse(WaitObject);Monitor.Exit(WaitObject); } }}using System;using System.IO;usingSystem.Threading;usingSystem.Runtime.InteropServices;usingSystem.Runtime.Remoting.Messaging;usingSystem.Security.Permissions;publicclassBulkImageProcAsync{publicconstStringImageBaseName = "tmpImage-";publicconstintnumImages = 200;publicconstintnumPixels = 512 * 512;publicstaticintprocessImageRepeats = 20;publicstaticintNumImagesToFinish = numImages;publicstaticObject[] NumImagesMutex = newObject[0];publicstaticObject[] WaitObject = newObject[0];publicclassImageStateObject {publicbyte[] pixels;publicintimageNum;publicFileStreamfs; }“Asynchronous File I/O”http://msdn.microsoft.com/en-us/library/kztecsys.aspxState of Asynchronous I/O
  • 19. letProcessImageAsynci =async { useinStream = File.OpenRead(sprintf"Image%d.tmp"i)let! pixels = inStream.AsyncRead(numPixels)let pixels' = ProcessImage(pixels, i)useoutStream = File.OpenWrite(sprintf"Image%d.done"i)do!outStream.AsyncWrite(pixels') }letProcessImagesAsync() =let tasks = [ foriin 1..numImages ->ProcessImageAsync(i) ]letparallelTasks = Async.Parallel tasksAsync.RunSynchronouslyparallelTasksWhy Isn’t it This Easy?
  • 20. Read streamasynchronouslyletProcessImageAsynci =async { useinStream = File.OpenRead(sprintf"Image%d.tmp"i)let! pixels = inStream.AsyncRead(numPixels)let pixels' = ProcessImage(pixels, i)useoutStream = File.OpenWrite(sprintf"Image%d.done"i)do!outStream.AsyncWrite(pixels') }letProcessImagesAsync() =let tasks = [ for i in 1..numImages ->ProcessImageAsynci ]letparallelTasks = Async.Parallel tasksAsync.RunSynnchronouslyparallelTasksThis object coordinatesWrite stream asynchronouslyGenerate the tasks and queue them in parallel“!” = “asynchronous”Digging Deeper…
  • 21. letgetHtml (url:string) =async { let request = WebRequest.Createurluse! response = request.AsyncGetResponse()use stream = response.GetResponseStream()use reader = newStreamReader(stream)return! reader.AsyncReadToEnd() }What we’re really writingletgetHtml (url:string) =async.Delay(fun () ->let request = WebRequest.Createurlasync.Bind(request.AsyncGetResponse(), funresponse ->async.Using(response, fun response ->async.Using(response.GetResponseStream(), fun stream ->async.Using(new StreamReader(stream), fun reader ->reader.AsyncReadToEnd())))))
  • 22. How does it work?Success ContinuationAsync<T>Execution RequestException ContinuationCancellation Continuation
  • 23. Anatomy of an Async OperationAsync operationsBegin/EndtypeSystem.Net.WebRequestwithmemberthis.AsyncGetRequestStream() =Async.BuildPrimitive(this.BeginGetRequestStream, this.EndGetRequestStream)
  • 24. What Do We Get For Free?Code that makes senseException propagationCancellation checkingSimple resource lifetime management
  • 27. Data Parallel ProgrammingPLINQEnable F# developers to leverage parallel hardwareAbstracts away parallelism detailsPartitions and merges data intelligentlyWorks on any seq<'a>/IEnumerable<T>let q = ratings |> PSeq.adapt |> PSeq.filter(funp ->p.Name = movieName &&p.Rating >= 3.0 &&p.Rating <= 5.0) |> PSeq.sortBy(fun p ->p.Rating) |> PSeq.map(funp ->p.CustomerId)
  • 28. Task Parallel ProgrammingEnable F# developers to create tasks in parallelletcomputeHash path algorithm =async { use stream = File.OpenRead pathlet! bytes = stream.AsyncRead(intstream.Length)let crypt = HashAlgorithm.Create algorithmreturncrypt.ComputeHash bytes }let algorithms = ["MD5";"SHA1";"SHA256";"SHA384";"SHA512"]let [|md5;sha1;sha256;sha384;sha512|] =Async.RunSynchronously(Async.Parallel [for algorithm in algorithms ->computeHash path algorithm])
  • 29. Task Parallel + Async WorkflowsTPL Tasks integrated in .NET 4.0 Async WorkflowsIntegrate with pre-defined tasksCalculate FuturesletgetStreamData (uri:string) =async { let request = WebRequest.Createuriuse! response = request.AsyncGetResponse()return [use stream = response.GetResponseStream()use reader = new StreamReader(stream)while not reader.EndOfStreamdoyieldreader.ReadLine()] }let result = Async.CreateAsTask <| getStreamDatamyUrido result.Start()letresultValue = result.Value
  • 31. Actor Model ConcurrencyLots of little tasksEach process does one taskAnt ColonyAnts are processes sending messages to each other
  • 32. Actor Model in Action…let (<--) (m:'aMailboxProcessor) msg = m.Post(msg)typePinger = PongtypePonger = Ping ofMailboxProcessor<Pinger> | Stopletponger = newMailboxProcessor<Ponger>(funinbox ->let rec loop pongCount =async { let! msg = inbox.Receive()matchmsgwith | Ping outbox -> outbox <-- Pongreturn! loop(pongCount + 1) | Stop -> return () } loop 0)
  • 33. Actor Model in Action…letpinger count pong =  newMailboxProcessor<Pinger>(funinbox ->    let rec sendPing() =       async { pong <-- Ping(inbox)              return! loop (count - 1) }    and loop pingsLeft =      async { let! msg = inbox.Receive()              matchmsgwith              | Pong ->                  ifpingsLeft > 0 then                    pong <-- Ping(inbox)                    return! loop(pingsLeft - 1)                  else                     pong <-- Stop                    return () }    sendPing())
  • 37. What’s in Store for 2010?
  • 38. Ways to Learn F#http://www.fsharp.netF# Interactive (FSI)Language SpecificationF# Team BlogsF# (FSharp) Discussion DLhttp://cs.hubfs.netCodePlex F# Samples.NET ReflectorGo to Definition
  • 40. Resources - BlogsDon Symehttp://blogs.msdn.com/dsyme/Luke Hobanhttp://blogs.msdn.com/lukeh/Brian McNamarahttp://lorgonblog.spaces.live.com/Chris Smithhttp://blogs.msdn.com/chrsmith/Jomo Fisherhttp://blogs.msdn.com/jomo_fisher/Planet F#http://feeds.feedburner.com/planet_fsharp

Editor's Notes

  • #12: What is the Problem?Multithreaded programming is hard todayDoable by only a subgroup of senior specialistsParallel patterns are not prevalent, well known, nor easy to implementSo many potential problemsRaces, deadlocks, livelocks, lock convoys, cache coherency overheads, lost event notifications, broken serializability, priority inversion, and so on…Businesses have little desire to go deepBest developers should focus on business value, not concurrencyNeed simple ways to allow all developers to write concurrent code