SlideShare a Scribd company logo
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 code
ShriKant 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 abstraction
Sergey Platonov
 
Clang tidy
Clang tidyClang tidy
Clang tidy
Yury Yafimachau
 
NS2 Object Construction
NS2 Object ConstructionNS2 Object Construction
NS2 Object Construction
Teerawat Issariyakul
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
Teerawat 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 212
Mahmoud Samir Fayed
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
cqtt191
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Hithem Ahmed
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Sergey Platonov
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
Rafael Winterhalter
 
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
Mahmoud Samir Fayed
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
Sergey Platonov
 
Java 14 features
Java 14 featuresJava 14 features
Java 14 features
Aditi Anand
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
Rafael Winterhalter
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
Alexander 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 196
Mahmoud 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 Java
Doug 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

09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
baran19901990
 
Principles of programming languages
Principles of programming languagesPrinciples of programming languages
Principles of programming languages
IT Training and Job Placement
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
baran19901990
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
Hoang Nguyen
 
Datatype
DatatypeDatatype
Datatype
baran19901990
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
baran19901990
 
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
Akshay Nagpurkar
 
Unit 5
Unit 5Unit 5
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
Vasavi College of Engg
 
Unit 4
Unit 4Unit 4
principles of programming languages
principles of programming languages principles of programming languages
principles of programming languages
Lakshmi Prasad
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
Vasavi College of Engg
 
Principles of programming languages. Detail notes
Principles of programming languages. Detail notesPrinciples of programming languages. Detail notes
Principles of programming languages. Detail notes
VIKAS SINGH BHADOURIA
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
Vasavi College of Engg
 

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

Thread
ThreadThread
Thread
phanleson
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
Guy Korland
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
Devnology
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ganesh Samarthyam
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
Duong 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 - Threads
WebStackAcademy
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
Tomasz Kowalczewski
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
Sri Prasanna
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
sujatha629799
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
Rajesh Verma
 
Operating System lab
Operating System labOperating System lab
Operating System lab
Seyed Ehsan Beheshtian
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
Minh Tran
 
Thread 1
Thread 1Thread 1
Thread 1
RAVI MAURYA
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 

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

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 

Recently uploaded (20)

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 

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.