SlideShare a Scribd company logo
1 of 18
Yudong Li
May 2009
   A concurrent program needs to perform several
    possibly unrelated tasks at the same time.
   The most common tool to deal with concurrency is
    thread.
   Thread is an individual entity of execution from
    the main programs, and thread can give birth to
    another thread.
   Concurrency when multiple threads created.
   Multi-thread is not really simultaneous execution,
    but with time slot allocation with certain algorithm
    (e.g. Round Robin)
   Two ways
       Extends java.lang.Thread class
       Implement java.lang.Runnable interface
   Steps
       Create a thread
       Implement run() function
       Execute
class MyThreadA implements Runnable{
class MyThreadA extends Thread{
                                                       public void run(){
   public void run(){                                    for(int i=0;i<5;i++){
     for(int i=0;i<5;i++){                                 System.out.println(“Thread A is running”).
       System.out.println(“Thread A is running”).        }
     }                                                 }
   }                                                }
}
class MyThreadB extends Thread{                     class MyThreadA implements Runnable{
   public void run(){                                  public void run(){
                                                         for(int i=0;i<5;i++){
     for(int i=0;i<5;i++){
                                                           System.out.println(“Thread A is running”).
       System.out.println(“Thread B is running”).        }
     }                                                 }
   }                                                }
}
                                                    class Test{
class Test{                                            public static void main(String[] args){
                                                         Thread t1 = new Thread(new MyThreadA());
    Public static void main(String[] args){              Thread t2 = new Thread(new MyThreadB());
      new MyThreadA().start();                           t1.start();
                                                         t2.start();
      new MyThreadB().start();                         }
    }                                               }
}
   The result is not deterministic
   Can add priority to control the order
       static int MAX_PRIORITY
       static int MIN_PRIORITY
       static int NORM_PRIORITY
   Control.Concurrent module
   data ThreadId
       An abstract type representing a handle to a thread.
   forkIO :: IO() -> IO ThreadId
       Takes an IO action as its argument, and spawns it as
        a concurrent thread. Once created, run concurrently
        with other threads.
import Control.Concurrent (forkIO)
import IO
printThread :: IO()
printThread = do {
  forkIO(hPutStr stdout “ThreadA”);
  forkIO(hPutStr stdout “ThreadB”);
  hPutStr stdout “ThreadC”
}
   Haskell thread is light-weight
   The print result differs from Java:
       Java: ThreadA is running…ThreadB is running…
       Haskell: TThThrhrereaeadadCdAB…
   Several threads modify same sharing resource
   Use implicitly lock -- synchronized -- to make
    resource accessible to only one thread at a time.
      class Account {
                int balance;
                synchronized public void deposit(double amount){
                                    balance = balance – amount;
                }
                public void withdraw(double amount){
                                    depoist(-amount)
                }
      }
        void transfer(Account from, Account to, Double amount){
                from.withDraw(amount);
                to.deposit(amount);
      }
   Intermediate State
        During the deposit and withdraw, other thread can observe a state
    that money in neither of the two accounts.
        Add lock:
                from.lock(); to.lock();
                from.withdraw(amount); to.depoist(amount);
                from.unlock(); to.unlock();

   Deadlock
                Account A                      Account B
    Thread A            --------------------->   lock A, waiting for the lock B
    Thread B            <---------------------   lock B, waiting for the lock A

       During the process of competing for the lock, each thread will hold
    one lock and wait indefinitely for another lock that will never come.
   A concurrency control mechanism analogous to
    database transactions for controlling access to
    shared memory in concurrent computing. (wiki.)
     Execute body without lock
     Write all the calls and values into a log
     After execution finishes, validate the log with real
      value, commit if success or retry if failed.
Running STM Operations              TVar Operation
atomically :: STM a -> IO a         newTVar :: a -> STM (TVar a)
retry :: STM a                      readTVar :: TVar a -> STM a
orElse :: STM a -> STM a -> STM a   writeTVar :: TVar a -> a -> STM()
limitedWithdraw :: Account -> Int -> STM()
limitedWithdraw acc amount = atomically do {
  bal <- readTVar acc;
  check (amount <= 0 || amount <= bal);
    writeTVar acc (bal – amount)
}
check :: Bool -> STM()
check True = return ()
check False = retry
   Logically occur at a single instant of time
   Intermediate states are not visible to others
   Modifying shared memory or resource without
    worrying about other threads.
   No threads need to wait for access to resource.
   Different threads can modify disjoint data in
    the same data structure.
   Retry: when different threads constantly
    update the same variable, there is no way to
    achieve concurrency and some transactions
    may rollback many times.
   Commit overhead: particularly when programs
    do not perform much work inside transactions,
    the commit overhead appears to be very high.
   Transaction content: In order to make rollback
    available, there is a restriction on what
    functions can be done during a transaction.
    Especially for I/O functions, since its hard to
    undone those functions, it is not allowed to do
    so.
       It might be possible to use buffers to temporarily
        store those operations and execute it after the thread
        commits. But too much cost.
   Haskell is one of the first languages that
    integrates STM in its mainstream distribution.
   Also lots of implementations in other
    languages like C++, C#, Java. But none of them
    include STM in its distribution.
   Some concept are easy to define in Haskell, but
    difficult in OO languages, like Retry or Monad.
Concurrency in Programming Languages

More Related Content

What's hot

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Sergey Platonov
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting StartedTeerawat Issariyakul
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212Mahmoud Samir Fayed
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
 
The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196Mahmoud Samir Fayed
 
Java 14 features
Java 14 featuresJava 14 features
Java 14 featuresAditi Anand
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approachAlexander Granin
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196Mahmoud Samir Fayed
 
Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Adam Mukharil Bachtiar
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 

What's hot (20)

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
NS2 Object Construction
NS2 Object ConstructionNS2 Object Construction
NS2 Object Construction
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
 
Java 14 features
Java 14 featuresJava 14 features
Java 14 features
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196
 
Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)Algorithm and Programming (Looping Structure)
Algorithm and Programming (Looping Structure)
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 

Viewers also liked

Viewers also liked (14)

09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
 
Principles of programming languages
Principles of programming languagesPrinciples of programming languages
Principles of programming languages
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Datatype
DatatypeDatatype
Datatype
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 
Unit 4
Unit 4Unit 4
Unit 4
 
principles of programming languages
principles of programming languages principles of programming languages
principles of programming languages
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
Principles of programming languages. Detail notes
Principles of programming languages. Detail notesPrinciples of programming languages. Detail notes
Principles of programming languages. Detail notes
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 

Similar to Concurrency in Programming Languages

Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)Sri Prasanna
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptxcreativegamerz00
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topicsRajesh Verma
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 

Similar to Concurrency in Programming Languages (20)

Thread
ThreadThread
Thread
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
Operating System lab
Operating System labOperating System lab
Operating System lab
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Thread 1
Thread 1Thread 1
Thread 1
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 

Recently uploaded

UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 

Recently uploaded (20)

UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 

Concurrency in Programming Languages

  • 2. A concurrent program needs to perform several possibly unrelated tasks at the same time.  The most common tool to deal with concurrency is thread.  Thread is an individual entity of execution from the main programs, and thread can give birth to another thread.  Concurrency when multiple threads created.  Multi-thread is not really simultaneous execution, but with time slot allocation with certain algorithm (e.g. Round Robin)
  • 3. Two ways  Extends java.lang.Thread class  Implement java.lang.Runnable interface  Steps  Create a thread  Implement run() function  Execute
  • 4. class MyThreadA implements Runnable{ class MyThreadA extends Thread{ public void run(){ public void run(){ for(int i=0;i<5;i++){ for(int i=0;i<5;i++){ System.out.println(“Thread A is running”). System.out.println(“Thread A is running”). } } } } } } class MyThreadB extends Thread{ class MyThreadA implements Runnable{ public void run(){ public void run(){ for(int i=0;i<5;i++){ for(int i=0;i<5;i++){ System.out.println(“Thread A is running”). System.out.println(“Thread B is running”). } } } } } } class Test{ class Test{ public static void main(String[] args){ Thread t1 = new Thread(new MyThreadA()); Public static void main(String[] args){ Thread t2 = new Thread(new MyThreadB()); new MyThreadA().start(); t1.start(); t2.start(); new MyThreadB().start(); } } } }
  • 5. The result is not deterministic  Can add priority to control the order  static int MAX_PRIORITY  static int MIN_PRIORITY  static int NORM_PRIORITY
  • 6. Control.Concurrent module  data ThreadId  An abstract type representing a handle to a thread.  forkIO :: IO() -> IO ThreadId  Takes an IO action as its argument, and spawns it as a concurrent thread. Once created, run concurrently with other threads.
  • 7. import Control.Concurrent (forkIO) import IO printThread :: IO() printThread = do { forkIO(hPutStr stdout “ThreadA”); forkIO(hPutStr stdout “ThreadB”); hPutStr stdout “ThreadC” }
  • 8. Haskell thread is light-weight  The print result differs from Java:  Java: ThreadA is running…ThreadB is running…  Haskell: TThThrhrereaeadadCdAB…
  • 9. Several threads modify same sharing resource  Use implicitly lock -- synchronized -- to make resource accessible to only one thread at a time. class Account { int balance; synchronized public void deposit(double amount){ balance = balance – amount; } public void withdraw(double amount){ depoist(-amount) } } void transfer(Account from, Account to, Double amount){ from.withDraw(amount); to.deposit(amount); }
  • 10. Intermediate State During the deposit and withdraw, other thread can observe a state that money in neither of the two accounts. Add lock: from.lock(); to.lock(); from.withdraw(amount); to.depoist(amount); from.unlock(); to.unlock();  Deadlock Account A Account B Thread A ---------------------> lock A, waiting for the lock B Thread B <--------------------- lock B, waiting for the lock A During the process of competing for the lock, each thread will hold one lock and wait indefinitely for another lock that will never come.
  • 11. A concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. (wiki.)  Execute body without lock  Write all the calls and values into a log  After execution finishes, validate the log with real value, commit if success or retry if failed.
  • 12. Running STM Operations TVar Operation atomically :: STM a -> IO a newTVar :: a -> STM (TVar a) retry :: STM a readTVar :: TVar a -> STM a orElse :: STM a -> STM a -> STM a writeTVar :: TVar a -> a -> STM()
  • 13. limitedWithdraw :: Account -> Int -> STM() limitedWithdraw acc amount = atomically do { bal <- readTVar acc; check (amount <= 0 || amount <= bal); writeTVar acc (bal – amount) } check :: Bool -> STM() check True = return () check False = retry
  • 14. Logically occur at a single instant of time  Intermediate states are not visible to others  Modifying shared memory or resource without worrying about other threads.  No threads need to wait for access to resource.  Different threads can modify disjoint data in the same data structure.
  • 15. Retry: when different threads constantly update the same variable, there is no way to achieve concurrency and some transactions may rollback many times.  Commit overhead: particularly when programs do not perform much work inside transactions, the commit overhead appears to be very high.
  • 16. Transaction content: In order to make rollback available, there is a restriction on what functions can be done during a transaction. Especially for I/O functions, since its hard to undone those functions, it is not allowed to do so.  It might be possible to use buffers to temporarily store those operations and execute it after the thread commits. But too much cost.
  • 17. Haskell is one of the first languages that integrates STM in its mainstream distribution.  Also lots of implementations in other languages like C++, C#, Java. But none of them include STM in its distribution.  Some concept are easy to define in Haskell, but difficult in OO languages, like Retry or Monad.