SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

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

Semelhante a 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
 

Semelhante a 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
 

Último

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 DevelopmentsTrustArc
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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 WorkerThousandEyes
 
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 2024The Digital Insurer
 
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 TerraformAndrey Devyatkin
 

Último (20)

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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
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
 
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
 

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.