SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 

Dernier (20)

Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 

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.