SlideShare une entreprise Scribd logo
1  sur  74
Télécharger pour lire hors ligne
Functions +
Messages + Concurrency
       = Erlang


    Joe Armstrong
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

      Fault                 Multicore
    tolerance
Problem domain

Highly concurrent (hundreds of thousands of parallel
activities)
Real time
Distributed
High Availability (down times of minutes/year – never down)
Complex software (million of lines of code)
Continuous operation (years)
Continuous evolution
In service upgrade
Erlang
Very light-weight processes
Very fast message passing
Total separation between processes
Automatic marshalling/demarshalling
Fast sequential code
Strict functional code
Dynamic typing
Transparent distribution
Compose sequential AND concurrent code
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

      Fault                 Multicore
    tolerance
2002
Fraction of Chip reachable in one clock cycle




 [source] Erik Hagersten http://www.sics.se/files/projects/
 multicore/day2007/ErikH-intro.pdf
Clock Frequency




Clock frequency trend for Intel Cpus (Linux Journal)


Read: Clock rate verses IPC. The end of the road for
Conventional Microarchitectures. Agarwal et.al 2000
Due to hardware changes:


Each year your sequential
 programs will go slower

Each year your concurrent
 programs will go faster
2005 – 2015
Paradigm shift in
      CPU
 architectures
Three New
Architectures
ONE - Multi core
TWO -
GPUs

Cell Computers
THREE – network on
Intel Polaris – 2007   Chip (NOC)
1 Tflop at 24 Watts
ASCI RED- 1997   - 1997
                 - First machine over 1 Tera
                  Flop
                 - 2,500 sq ft floor space
                  104 cabinets
                 - 9326 pentium pro
                  processors
                 - 850 KW
2 cores won't hurt you
4 cores will hurt a little
8 cores will hurt a bit
16 will start hurting
32 cores will hurt a lot (2009)
...
1 M cores ouch (2019)
    (complete paradigm shift)

1997 1 Tflop = 850 KW
2007 1 Tflop = 24 W (factor 35,000)
2017 1 Tflop = ?
Goal
Make my program run N times faster on an
N core CPU with
 no changes to the program
 no pain and suffering

Can we do this?

Yes     Sometimes (often)
Due to hardware changes:

Each year your sequential
 programs will go slower

Each year your concurrent
 programs will go faster
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

     Fault                  Multicore
   tolerance
To make
a fault-tolerant system
   you need at least


      two
      computers
If one computer crashes
the other must take over




= No Shared data
= Distributed programming
= Pure Message passing
To do fault tolerant computing we
need at least two isolated computers




     = Concurrent programming
       with pure message passing
To do very fault tolerant computing
we need lots of isolated computers




       = Scalable
Fault tolerance
 Distribution
 Concurrency
  Scalability

are inseparable
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

      Fault                 Multicore
    tolerance
Two models of Concurrency
Shared Memory
 - mutexes
 - threads
 - locks

Message Passing
 - messages
 - processes
Shared
  Memory
Programming
Shared memory
Problem 1
            Your program
            crashes in
            the critical region
            having corrupted
            memory
Problem 2


Sweden           ?           Australia




 Where do we (physically) locate the
 shared memory?
 Impossible to get low-latency and make
 consistent (violates laws of physics)
Thread Safety
Erlang programs are
automatically thread
safe if they don't use
an external resource.
Sharing is the
 property that
   prevents
fault tolerance
      and
Thread safety
Message
  Passing
Concurrency
No sharing
Pure message passing
No locks
Lots of computers (= fault tolerant
scalable ...)
Functional programming (no side
effects)
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

      Fault                 Multicore
    tolerance
What is COP?

                                        Machine


                                        Process

                                        Message


               Large number of processes
               Complete isolation between processes
               Location transparency
               No Sharing of data
               Pure message passing systems
Why is COP nice?

We intuitively understand concurrency
The world is parallel
The world is distributed
Making a real-world application is based on
observation of the concurrency patterns and
message channels in the application
Easy to make scalable, distributed applications
Concurrency Oriented Programming

 A style of programming where
concurrency is used to structure the
application
                                  My first message is that
Large numbers of processes              concurrency
Complete isolation of          is best regarded as a program
 processes
                                    structuring principle”
No sharing of data
Location transparency
Pure message passing         Structured concurrent programming
                                          – Tony Hoare
Examples of COP architectures
remember – no shared memory
– pure message passing

Email
Google – map – reduce (450,000
machines)
People (no shared state, message
passing via voiceGrams, waving
arms, non-reliable etc.)
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

      Fault                 Multicore
    tolerance
Functional programming
Scary stuff
Or easy?


fac(0) -> 1;
fac(N) -> N*fac(N-1).
Why is FP good?
Side effects are strictly controlled


              If you call the
         same function twice with
           the same arguments
      it should return the same value
Referential transparency

  In    Out      In,S   Out,S'




 S     S'


OOP              FP
Functional programming languages
    FLPs carry state with them
   wherever the flow of control
   goes. Different FPLs provide
     different notations and        In,S   Out,S'
    mechanisms for hiding this
          from the user.

    In Erlang we hide the state
    in a process. In Haskell in a
               monad

  FLPs have are based on a formal   FP
        mathematical model
   Lambda calculus (Pi calc, CSP)
Why is this important?
Compositional properties
Output of one function must be input to next
f(g(h(i(k(X)))))
Echo “foo” | k | i | h | g | f
No mutable state means nothing to lock and
automatic thread safety when parallelised
Can reuse pure functions
FP is on the rise

 Haskell
 Erlang
 O'Caml, F#
BAD STUFF
                                           Very very bad
Threads

Sharing

Mutexes - Locks

Synchronized methods

Mutable state
                           Mutable state is the root of all evil


           FPLs have no mutable state
GOOD STUFF
Processes
Controlled side effects
Pure functions
Copying
Pure Message passing
Failure detection
Concurrent
   programming             Functional
                          programming


Concurrency
 Oriented
programming
                 Erlang

      Fault                 Multicore
    tolerance
Erlang in 11 Minutes

Sequential Erlang 5 examples
Concurrent Erlang 2 examples
Distributed Erlang 1 example
Fault-tolerant Erlang 2 examples
Bit syntax 1 example
Sequential Erlang

                Factorial   -module(math).
                            -export([fac/1]).
  Dynamic types
  Pattern matching          fac(N) when N > 0 -> N*fac(N-1);
  No mutable data           fac(0) -> 1
  structures
                            > math:fac(25).
Binary Tree Search           15511210043330985984000000


  lookup(Key, {Key, Val,_,_}) -> {ok, Val};
  lookup(Key, {Key1,Val,S,B}) when Key < Key1 ->
     lookup(Key, S);
  lookup(Key, {Key1, Val, S, B})->
     lookup(Key, B);
  lookup(key, nil) ->
     not_found.
Sequential Erlang

append   append([H|T], L) -> [H|append(T, L)];
         append([],    L) -> L.

sort     sort([Pivot|T]) ->
            sort([X||X <- T, X < Pivot]) ++
            [Pivot] ++
             sort([X||X <- T, X >= Pivot]);
         sort([]) -> [].

         > Adder = fun(N) -> fun(X) -> X + N end end.
 adder   #Fun
         > G = Adder(10).
         #Fun
         > G(5).
         15
Concurrent Erlang

spawn      Pid = spawn(fun() -> loop(0) end)

 send      Pid ! Message,
           .....

 receive   receive
               Message1 ->
                  Actions1;
               Message2 ->
                  Actions2;
                  ...
               after Time ->
                  TimeOutActions
           end




           The concurrency is in the language NOT the OS
Distributed Erlang

Pid = spawn(Fun@Node)

alive(Node),
.....

not_alive(Node)
Fault-tolerant Erlang

     ...
     case (catch foo(A, B)) of
         {abnormal_case1, Y} ->
            ...
         {'EXIT', Opps} ->
            ...
         Val ->
            ...
     end,
     ...

     foo(A, B) ->
        ...
        throw({abnormal_case1, ...})
Monitor a process

   ...
   process_flag(trap_exit, true),
   Pid = spawn_link(fun() -> ... end),
   receive
         {'EXIT', Pid, Why} ->
         ...
   end
Bit Syntax - parsing IP datagrams

-define(IP_VERSION, 4).

-define(IP_MIN_HDR_LEN,5).
DgramSize = size(Dgram),
case Dgram of

 <<?IP_VERSION:4, HLen:4,
  SrvcType:8, TotLen:16, ID:16, Flgs:3,
                                                  This code parses the
  FragOff:13, TTL:8, Proto:8, HdrChkSum:16,
                                                  header and extracts
  SrcIP:32, DestIP:32, Body/binary>> when
                                                  the data from an IP
   HLen >= 5, 4*HLen =< DgramSize ->
    OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN),
                                                  protocol version 4

    <<Opts:OptsLen/binary,Data/binary>> = Body,   datagram
  ...
Bit syntax – unpacking MPEG data
Some code
loop() ->
   receive
      {email,From,Subject,Text} = Email ->
         {ok, S} = file:open(quot;inboxquot;,[append,write]),
         io:format(S, quot;~p.~nquot;,[Email]),
         file:close(S);
      {msg, From, Message} ->
         io:format(quot;msg (~s) ~s~nquot;, [From, Message]);
      {From, get, File} ->
         From ! file:read_file(File)
   end,
   loop().

Mike ! {email, quot;joequot;, quot;dinnerquot;, quot;see you at 18.00quot;}.

Helen ! {msg, quot;joequot;, quot;Can you buy some milk on your way
home?quot;}
Programming Multicore computers is difficult
because of shared mutable state.


Functional programming languages have no shared
state and no mutable state


Erlang has the right intrinsic properties for
programming multicore computers (concurrency
maps to the multiple CPUs, non-mutability means we
don't get any problems with memory corruption)
- Use “lots” of processes
- Avoid sequential bottlenecks
- Use “large computation”
  small data transfer (if
  possible)
- New abstractions (pmap,
  mapreduce)
Commercial projects
Ericsson AXD301 (part of “Engine”)
Ericsson GPRS system
Alteon (Nortel) SSL accelerator
Alteon (Nortel) SSL VPN
Teba Bank (credit card system – South Africa)
T-mobile SMS system (UK)
Kreditor (Sweden)
Synapse
Tail-f
jabber.org /uses ejabberd)
Twitter (uses ejabberd)
Lshift (RabbitMQ) AMQP (Advanced Message Queuing protocol)
More Info




Erlang Exchange – June 26 – 27.
www.erlang-exchange.com
Finally

  We've known how to program parallel
  computers for the last twenty years

We can make highly reliable fault tolerant
     distributed real-time systems

              ww.erlang.org
Questions?

Contenu connexe

Tendances

Comparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms SoftwareComparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms Software
l xf
 
Chapter Seven(1)
Chapter Seven(1)Chapter Seven(1)
Chapter Seven(1)
bolovv
 
Everybody be cool, this is a ROPpery
Everybody be cool, this is a ROPperyEverybody be cool, this is a ROPpery
Everybody be cool, this is a ROPpery
Vincenzo Iozzo
 
12109 microprocessor & programming
12109 microprocessor & programming12109 microprocessor & programming
12109 microprocessor & programming
Gaurang Thakar
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
Dmitri Nesteruk
 
4 compiler lab - Syntax Ana
4 compiler lab - Syntax Ana4 compiler lab - Syntax Ana
4 compiler lab - Syntax Ana
MashaelQ
 

Tendances (20)

Slides
SlidesSlides
Slides
 
Comparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms SoftwareComparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms Software
 
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
Attention-based Models (DLAI D8L 2017 UPC Deep Learning for Artificial Intell...
 
Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2
 
Verification with LoLA
Verification with LoLAVerification with LoLA
Verification with LoLA
 
Sstic 2015 detailed_version_triton_concolic_execution_frame_work_f_saudel_jsa...
Sstic 2015 detailed_version_triton_concolic_execution_frame_work_f_saudel_jsa...Sstic 2015 detailed_version_triton_concolic_execution_frame_work_f_saudel_jsa...
Sstic 2015 detailed_version_triton_concolic_execution_frame_work_f_saudel_jsa...
 
Dynamic Binary Analysis and Obfuscated Codes
Dynamic Binary Analysis and Obfuscated Codes Dynamic Binary Analysis and Obfuscated Codes
Dynamic Binary Analysis and Obfuscated Codes
 
Real Time Filtering on Embedded ARM
Real Time Filtering on Embedded ARMReal Time Filtering on Embedded ARM
Real Time Filtering on Embedded ARM
 
Chapter Seven(1)
Chapter Seven(1)Chapter Seven(1)
Chapter Seven(1)
 
Everybody be cool, this is a ROPpery
Everybody be cool, this is a ROPperyEverybody be cool, this is a ROPpery
Everybody be cool, this is a ROPpery
 
1 hour dive into erlang
1  hour dive into erlang1  hour dive into erlang
1 hour dive into erlang
 
Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
12109 microprocessor & programming
12109 microprocessor & programming12109 microprocessor & programming
12109 microprocessor & programming
 
Functional Programming With Python (EuroPython 2008)
Functional Programming With Python (EuroPython 2008)Functional Programming With Python (EuroPython 2008)
Functional Programming With Python (EuroPython 2008)
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 
Mp &mc programs
Mp &mc programsMp &mc programs
Mp &mc programs
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
 
Compiler Design Unit 1
Compiler Design Unit 1Compiler Design Unit 1
Compiler Design Unit 1
 
4 compiler lab - Syntax Ana
4 compiler lab - Syntax Ana4 compiler lab - Syntax Ana
4 compiler lab - Syntax Ana
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
 

En vedette

1300579454645 livro adm proc operacionais
1300579454645 livro adm proc operacionais1300579454645 livro adm proc operacionais
1300579454645 livro adm proc operacionais
PMP
 
Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Win
l xf
 
Lecture 6
Lecture  6Lecture  6
Lecture 6
Mr SMAK
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load BalancingScalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
Information Technology
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
dgnadt
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
zukun
 

En vedette (20)

1300579454645 livro adm proc operacionais
1300579454645 livro adm proc operacionais1300579454645 livro adm proc operacionais
1300579454645 livro adm proc operacionais
 
Introdução à Computação Aula 05 - Sistemas Operacionais (arquitetura do SO, p...
Introdução à Computação Aula 05 - Sistemas Operacionais (arquitetura do SO, p...Introdução à Computação Aula 05 - Sistemas Operacionais (arquitetura do SO, p...
Introdução à Computação Aula 05 - Sistemas Operacionais (arquitetura do SO, p...
 
Apostila de sistemas operacionais
Apostila de sistemas operacionaisApostila de sistemas operacionais
Apostila de sistemas operacionais
 
Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Win
 
Message Passing, Remote Procedure Calls and Distributed Shared Memory as Com...
Message Passing, Remote Procedure Calls and  Distributed Shared Memory as Com...Message Passing, Remote Procedure Calls and  Distributed Shared Memory as Com...
Message Passing, Remote Procedure Calls and Distributed Shared Memory as Com...
 
Lecture 6
Lecture  6Lecture  6
Lecture 6
 
message passing vs shared memory
message passing vs shared memorymessage passing vs shared memory
message passing vs shared memory
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with python
 
Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012
 
Android Application: Introduction
Android Application: IntroductionAndroid Application: Introduction
Android Application: Introduction
 
Functional style programming
Functional style programmingFunctional style programming
Functional style programming
 
Lec 03 set
Lec 03   setLec 03   set
Lec 03 set
 
What is Network Security?
What is Network Security?What is Network Security?
What is Network Security?
 
Serial Killers Presentation1
Serial Killers Presentation1Serial Killers Presentation1
Serial Killers Presentation1
 
SAN Review
SAN ReviewSAN Review
SAN Review
 
Android UI
Android UIAndroid UI
Android UI
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load BalancingScalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
 
CITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANCITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHAN
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
 

Similaire à Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-core (Joe Armstrong)

Joe armstrong erlanga_languageforprogrammingreliablesystems
Joe armstrong erlanga_languageforprogrammingreliablesystemsJoe armstrong erlanga_languageforprogrammingreliablesystems
Joe armstrong erlanga_languageforprogrammingreliablesystems
Sentifi
 
0.5mln packets per second with Erlang
0.5mln packets per second with Erlang0.5mln packets per second with Erlang
0.5mln packets per second with Erlang
Maxim Kharchenko
 
Erlang plus BDB: Disrupting the Conventional Web Wisdom
Erlang plus BDB: Disrupting the Conventional Web WisdomErlang plus BDB: Disrupting the Conventional Web Wisdom
Erlang plus BDB: Disrupting the Conventional Web Wisdom
guest3933de
 
Erlang及其应用
Erlang及其应用Erlang及其应用
Erlang及其应用
Feng Yu
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 

Similaire à Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-core (Joe Armstrong) (20)

Erlang
ErlangErlang
Erlang
 
Joe armstrong erlanga_languageforprogrammingreliablesystems
Joe armstrong erlanga_languageforprogrammingreliablesystemsJoe armstrong erlanga_languageforprogrammingreliablesystems
Joe armstrong erlanga_languageforprogrammingreliablesystems
 
An introduction to erlang
An introduction to erlangAn introduction to erlang
An introduction to erlang
 
Erlang OTP
Erlang OTPErlang OTP
Erlang OTP
 
Erlang, an overview
Erlang, an overviewErlang, an overview
Erlang, an overview
 
0.5mln packets per second with Erlang
0.5mln packets per second with Erlang0.5mln packets per second with Erlang
0.5mln packets per second with Erlang
 
0.5mln packets per second with Erlang
0.5mln packets per second with Erlang0.5mln packets per second with Erlang
0.5mln packets per second with Erlang
 
Concurrent programming1
Concurrent programming1Concurrent programming1
Concurrent programming1
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Erlang in 10 minutes
Erlang in 10 minutesErlang in 10 minutes
Erlang in 10 minutes
 
Erlang plus BDB: Disrupting the Conventional Web Wisdom
Erlang plus BDB: Disrupting the Conventional Web WisdomErlang plus BDB: Disrupting the Conventional Web Wisdom
Erlang plus BDB: Disrupting the Conventional Web Wisdom
 
Disrupt
DisruptDisrupt
Disrupt
 
Recursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, BangaloreRecursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, Bangalore
 
Erlang os
Erlang osErlang os
Erlang os
 
Erlang Developments: The Good, The Bad and The Ugly
Erlang Developments: The Good, The Bad and The UglyErlang Developments: The Good, The Bad and The Ugly
Erlang Developments: The Good, The Bad and The Ugly
 
Functional approach to packet processing
Functional approach to packet processingFunctional approach to packet processing
Functional approach to packet processing
 
Erlang及其应用
Erlang及其应用Erlang及其应用
Erlang及其应用
 
The Erlang Programming Language
The Erlang Programming LanguageThe Erlang Programming Language
The Erlang Programming Language
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 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?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 

Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-core (Joe Armstrong)

  • 1. Functions + Messages + Concurrency = Erlang Joe Armstrong
  • 2. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 3. Problem domain Highly concurrent (hundreds of thousands of parallel activities) Real time Distributed High Availability (down times of minutes/year – never down) Complex software (million of lines of code) Continuous operation (years) Continuous evolution In service upgrade
  • 4. Erlang Very light-weight processes Very fast message passing Total separation between processes Automatic marshalling/demarshalling Fast sequential code Strict functional code Dynamic typing Transparent distribution Compose sequential AND concurrent code
  • 5. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 7. Fraction of Chip reachable in one clock cycle [source] Erik Hagersten http://www.sics.se/files/projects/ multicore/day2007/ErikH-intro.pdf
  • 8. Clock Frequency Clock frequency trend for Intel Cpus (Linux Journal) Read: Clock rate verses IPC. The end of the road for Conventional Microarchitectures. Agarwal et.al 2000
  • 9.
  • 10. Due to hardware changes: Each year your sequential programs will go slower Each year your concurrent programs will go faster
  • 11. 2005 – 2015 Paradigm shift in CPU architectures
  • 13. ONE - Multi core
  • 15. THREE – network on Intel Polaris – 2007 Chip (NOC) 1 Tflop at 24 Watts
  • 16. ASCI RED- 1997 - 1997 - First machine over 1 Tera Flop - 2,500 sq ft floor space 104 cabinets - 9326 pentium pro processors - 850 KW
  • 17. 2 cores won't hurt you 4 cores will hurt a little 8 cores will hurt a bit 16 will start hurting 32 cores will hurt a lot (2009) ... 1 M cores ouch (2019) (complete paradigm shift) 1997 1 Tflop = 850 KW 2007 1 Tflop = 24 W (factor 35,000) 2017 1 Tflop = ?
  • 18. Goal Make my program run N times faster on an N core CPU with no changes to the program no pain and suffering Can we do this? Yes Sometimes (often)
  • 19. Due to hardware changes: Each year your sequential programs will go slower Each year your concurrent programs will go faster
  • 20. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 21. To make a fault-tolerant system you need at least two computers
  • 22. If one computer crashes the other must take over = No Shared data = Distributed programming = Pure Message passing
  • 23. To do fault tolerant computing we need at least two isolated computers = Concurrent programming with pure message passing
  • 24. To do very fault tolerant computing we need lots of isolated computers = Scalable
  • 25. Fault tolerance Distribution Concurrency Scalability are inseparable
  • 26. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 27. Two models of Concurrency Shared Memory - mutexes - threads - locks Message Passing - messages - processes
  • 30. Problem 1 Your program crashes in the critical region having corrupted memory
  • 31. Problem 2 Sweden ? Australia Where do we (physically) locate the shared memory? Impossible to get low-latency and make consistent (violates laws of physics)
  • 32.
  • 33.
  • 34. Thread Safety Erlang programs are automatically thread safe if they don't use an external resource.
  • 35. Sharing is the property that prevents fault tolerance and Thread safety
  • 37. No sharing Pure message passing No locks Lots of computers (= fault tolerant scalable ...) Functional programming (no side effects)
  • 38. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 39. What is COP? Machine Process Message Large number of processes Complete isolation between processes Location transparency No Sharing of data Pure message passing systems
  • 40. Why is COP nice? We intuitively understand concurrency The world is parallel The world is distributed Making a real-world application is based on observation of the concurrency patterns and message channels in the application Easy to make scalable, distributed applications
  • 41. Concurrency Oriented Programming A style of programming where concurrency is used to structure the application My first message is that Large numbers of processes concurrency Complete isolation of is best regarded as a program processes structuring principle” No sharing of data Location transparency Pure message passing Structured concurrent programming – Tony Hoare
  • 42. Examples of COP architectures remember – no shared memory – pure message passing Email Google – map – reduce (450,000 machines) People (no shared state, message passing via voiceGrams, waving arms, non-reliable etc.)
  • 43. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 46. Or easy? fac(0) -> 1; fac(N) -> N*fac(N-1).
  • 47. Why is FP good? Side effects are strictly controlled If you call the same function twice with the same arguments it should return the same value
  • 48. Referential transparency In Out In,S Out,S' S S' OOP FP
  • 49. Functional programming languages FLPs carry state with them wherever the flow of control goes. Different FPLs provide different notations and In,S Out,S' mechanisms for hiding this from the user. In Erlang we hide the state in a process. In Haskell in a monad FLPs have are based on a formal FP mathematical model Lambda calculus (Pi calc, CSP)
  • 50. Why is this important? Compositional properties Output of one function must be input to next f(g(h(i(k(X))))) Echo “foo” | k | i | h | g | f No mutable state means nothing to lock and automatic thread safety when parallelised Can reuse pure functions
  • 51. FP is on the rise Haskell Erlang O'Caml, F#
  • 52. BAD STUFF Very very bad Threads Sharing Mutexes - Locks Synchronized methods Mutable state Mutable state is the root of all evil FPLs have no mutable state
  • 53. GOOD STUFF Processes Controlled side effects Pure functions Copying Pure Message passing Failure detection
  • 54. Concurrent programming Functional programming Concurrency Oriented programming Erlang Fault Multicore tolerance
  • 55.
  • 56. Erlang in 11 Minutes Sequential Erlang 5 examples Concurrent Erlang 2 examples Distributed Erlang 1 example Fault-tolerant Erlang 2 examples Bit syntax 1 example
  • 57. Sequential Erlang Factorial -module(math). -export([fac/1]). Dynamic types Pattern matching fac(N) when N > 0 -> N*fac(N-1); No mutable data fac(0) -> 1 structures > math:fac(25). Binary Tree Search 15511210043330985984000000 lookup(Key, {Key, Val,_,_}) -> {ok, Val}; lookup(Key, {Key1,Val,S,B}) when Key < Key1 -> lookup(Key, S); lookup(Key, {Key1, Val, S, B})-> lookup(Key, B); lookup(key, nil) -> not_found.
  • 58. Sequential Erlang append append([H|T], L) -> [H|append(T, L)]; append([], L) -> L. sort sort([Pivot|T]) -> sort([X||X <- T, X < Pivot]) ++ [Pivot] ++ sort([X||X <- T, X >= Pivot]); sort([]) -> []. > Adder = fun(N) -> fun(X) -> X + N end end. adder #Fun > G = Adder(10). #Fun > G(5). 15
  • 59. Concurrent Erlang spawn Pid = spawn(fun() -> loop(0) end) send Pid ! Message, ..... receive receive Message1 -> Actions1; Message2 -> Actions2; ... after Time -> TimeOutActions end The concurrency is in the language NOT the OS
  • 60. Distributed Erlang Pid = spawn(Fun@Node) alive(Node), ..... not_alive(Node)
  • 61. Fault-tolerant Erlang ... case (catch foo(A, B)) of {abnormal_case1, Y} -> ... {'EXIT', Opps} -> ... Val -> ... end, ... foo(A, B) -> ... throw({abnormal_case1, ...})
  • 62. Monitor a process ... process_flag(trap_exit, true), Pid = spawn_link(fun() -> ... end), receive {'EXIT', Pid, Why} -> ... end
  • 63. Bit Syntax - parsing IP datagrams -define(IP_VERSION, 4). -define(IP_MIN_HDR_LEN,5). DgramSize = size(Dgram), case Dgram of <<?IP_VERSION:4, HLen:4, SrvcType:8, TotLen:16, ID:16, Flgs:3, This code parses the FragOff:13, TTL:8, Proto:8, HdrChkSum:16, header and extracts SrcIP:32, DestIP:32, Body/binary>> when the data from an IP HLen >= 5, 4*HLen =< DgramSize -> OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN), protocol version 4 <<Opts:OptsLen/binary,Data/binary>> = Body, datagram ...
  • 64. Bit syntax – unpacking MPEG data
  • 65. Some code loop() -> receive {email,From,Subject,Text} = Email -> {ok, S} = file:open(quot;inboxquot;,[append,write]), io:format(S, quot;~p.~nquot;,[Email]), file:close(S); {msg, From, Message} -> io:format(quot;msg (~s) ~s~nquot;, [From, Message]); {From, get, File} -> From ! file:read_file(File) end, loop(). Mike ! {email, quot;joequot;, quot;dinnerquot;, quot;see you at 18.00quot;}. Helen ! {msg, quot;joequot;, quot;Can you buy some milk on your way home?quot;}
  • 66. Programming Multicore computers is difficult because of shared mutable state. Functional programming languages have no shared state and no mutable state Erlang has the right intrinsic properties for programming multicore computers (concurrency maps to the multiple CPUs, non-mutability means we don't get any problems with memory corruption)
  • 67.
  • 68.
  • 69.
  • 70. - Use “lots” of processes - Avoid sequential bottlenecks - Use “large computation” small data transfer (if possible) - New abstractions (pmap, mapreduce)
  • 71. Commercial projects Ericsson AXD301 (part of “Engine”) Ericsson GPRS system Alteon (Nortel) SSL accelerator Alteon (Nortel) SSL VPN Teba Bank (credit card system – South Africa) T-mobile SMS system (UK) Kreditor (Sweden) Synapse Tail-f jabber.org /uses ejabberd) Twitter (uses ejabberd) Lshift (RabbitMQ) AMQP (Advanced Message Queuing protocol)
  • 72. More Info Erlang Exchange – June 26 – 27. www.erlang-exchange.com
  • 73. Finally We've known how to program parallel computers for the last twenty years We can make highly reliable fault tolerant distributed real-time systems ww.erlang.org