SlideShare a Scribd company logo
1 of 19
Download to read offline
Catching Race Conditions
   An Extremely Difficult Task
Statically detecting race conditions in a
program using multiple semaphores is NP-hard.
Thus, no efficient algorithms are available. We
have to use human debugging skills.
It is virtually impossible to catch race
conditions dynamically because hardware must
examine every memory access.
So, we shall use a few examples to illustrate
some subtle race conditions.

                                             1
Problem Statement

Two groups, A and B, of processes exchange
messages.
Each process in A runs a function T_A(), and
each process in B runs a function T_B().
Both T_A() and T_B() have an infinite loop
and never stop.
In the following, we show execution sequences
that cause race conditions. You can always
find a correct execution sequence without race
conditions.
                                                 2
Processes in group A    Processes in group B

T_A()                   T_B()
{                       {
  while (1) {             while (1) {
    // do something         // do something
    Ex. Message             Ex. Message
    // do something         // do something
  }                       }
}                       }



                                                3
What is Exchange Message?
When a process in A makes a message available,
it can continue only if it receives a message
from a process in B who has successfully
retrieves A’s message.
Similarly, when a process in B makes a message
available, it can continue only if it receives a
message from a process in A who has
successfully retrieves B’s message.
How about exchanging business cards?
                                              4
Watch for Race Conditions
• Suppose process A1 presents its message for B
  to retrieve. If A2 comes for message exchange
  before B retrieves A1’s, will A2’s message
  overwrites A1’s?
• Suppose B has already retrieved A1’s message.
  Is it possible that when B presents its message,
  A2 picks it up rather than A1?
• Thus, the messages between A and B must be
  well-protected to avoid race conditions.
                                                     5
First Attempt
            sem A = 0, B = 0;        I am ready
            int Buf_A, Buf_B;
T_A()                        T_B()
{                            {
  int V_a;                     int V_b;
  while (1) {                  while (1) {
    V_a = ..;                    V_b = ..;
    B.signal();                  A.signal();
    A.wait();                    B.wait();
    Buf_A = V_a;                 Buf_B = V_b;
    V_a = Buf_B;                 V_b = Buf_A;
}                            }
       Wait for your card!                    6
First Attempt: Problem (a)
           Thread A           Thread B
        B.signal()
        A.wait()
                           A.signal()
Buf_B has no value, yet!   B.wait()
        Buf_A = V_a             Oops, it is too late!
        V_a = Buf_B
                           Buf_B = V_b

                                                  7
First Attempt: Problem (b)
    A1             A2          B1           B2
B.signal()
A.wait()
                           A.signal()
                           B.wait()
              B.signal()
              A.wait()
                           Buf_B = .
  Race Condition                        A.signal()
Buf_A = .
              Buf_A = .
                                                 8
What did we learn?

If there are shared data items,
always protect them properly.
Without a proper mutual exclusion,
race conditions are likely to occur.
In this first attempt, both global
variables Buf_A and Buf_B are
shared and should be protected.
                                       9
Second Attempt
             sem   A = B = 0;
             sem   Mutex = 1;
             int   Buf_A, Buf_B;
T_A()                    T_B()          protection???
{ int V_a; shake hands { int V_b;
  while (1) {               while (1) {
    B.signal();               A.signal();
    A.wait();                 B.wait();
      Mutex.wait();             Mutex.wait();
        Buf_A = V_a;              Buf_B = V_b;
      Mutex.signal();           Mutex.signal();
    B.signal();               A.signal();
    A.wait();                 B.wait();
      Mutex.wait();             Mutex.wait();
        V_a = Buf_B;              V_b = Buf_A;
                      offer
      Mutex.signal();           Mutex.signal();
  }                   My card
                            }
}                        }                        10
Second Attempt: Problem
          A1          A2           B
     B.signal()
     A.wait()
                              A.signal()
race condition
                              B.wait()
     Buf_A = ..
                             Buf_B = ..
                  B.signal()    hand shaking with
                  A.wait()      wrong person
                             A.signal()
                             B.wait()
                                              11
                  Buf_A = ..
What did we learn?
Improper protection is no better than no
protection, because it gives us an illusion
that data have been well-protected.
We frequently forgot that protection is
done by a critical section, which cannot
be divided.
Thus, protecting “here is my card”
followed by “may I have yours”
separately is not good enough.
                                              12
Third Attempt
                  sem Aready = Bready = 1;        ready to proceed
  job done        sem Adone = Bdone = 0;
                  int Buf_A, Buf_B;
            T_A()                   T_B()
            { int V_a;              { int V_b;
                while (1) {           while (1) {
only one A can Aready.wait();
Pass this point                         Bready.wait();
                    Buf_A = ..;           Buf_B = ..;
  here is my card
                    Adone.signal();       Bdone.signal();
      let me have
             yours Bdone.wait();          Adone.wait();
                    V_a = Buf_B;          V_b = Buf_A;
                  Aready.signal();      Bready.signal();
                }                     }
            }                       }
                                                            13
Third Attempt: Problem
          Thread A          Thread B
     Buf_A =
     Adone.signal()
     Bdone.wait()
ruin the original        Bdone.signal()
value of Buf_A           Adone.wait()
       … = Buf_B
       Aready.signal()         B is a slow
       ** loop back **         thread
     Aready.wait()
     Buf_A = …
       race condition    … = Buf_A           14
What did we learn?
Mutual exclusion for one group may not
prevent processes in other groups from
interacting with a process in this group.
It is common that we protect a shared
item for one group and forget other
possible, unintended accesses.
Protection must be applied uniformly to
all processes rather than within groups.

                                        15
Fourth Attempt
                  sem   Aready = Bready = 1;         ready to proceed
 job done         sem   Adone = Bdone = 0;
                  int   Buf_A, Buf_B;

               T_A()          wait/signal   T_B()
               { int V_a;      switched     { int V_b;
                  while (1) {                 while (1) {
I am the only A     Bready.wait();              Aready.wait();
                      Buf_A = ..;                 Buf_B = ..;
here is my card       Adone.signal();             Bdone.signal();
waiting for yours     Bdone.wait();               Adone.wait();
                      V_a = Buf_B;                V_b = Buf_A;
 Job done &
                    Aready.signal();            Bready.signal();
 next B please
                  }                           }
               }                            }
                                                                16
Fourth Attempt: Problem
       A1             A2                   B
Bready.wait()
Buf_A = …
Adone.signal()                   Buf_B = …
                                 Bdone.signal()
                                 Adone.wait()
                                 … = Buf_A
                                 Bready.signal()
                 Bready.wait()
                      ……         Hey, this one is for A1!!!
                 Bdone.wait()
                   … = Buf_B
                                                        17
What did we learn?
We use locks for mutual exclusion.
The owner, the one who locked the lock,
should unlock the lock.
In the above “solution,” Aready is
acquired by a process A but released by a
process B. This is risky!
In this case, a pure lock is more natural
than a binary semaphore.
                                        18
Conclusions
Detecting race conditions is difficult as it is an
NP-hard problem.
Hence, detecting race conditions is heuristic.
Incorrect mutual exclusion is no better than no
mutual exclusion.
Race conditions are sometimes very subtle.
They may appear at unexpected places.
Check the ThreadMentor tutorial pages for
more details and correct solutions.

                                                 19

More Related Content

What's hot

What's hot (20)

Expression trees
Expression treesExpression trees
Expression trees
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
 
B+ trees and height balance tree
B+ trees and height balance treeB+ trees and height balance tree
B+ trees and height balance tree
 
16. Concurrency Control in DBMS
16. Concurrency Control in DBMS16. Concurrency Control in DBMS
16. Concurrency Control in DBMS
 
concurrency-control
concurrency-controlconcurrency-control
concurrency-control
 
Bankers
BankersBankers
Bankers
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Multi threading
Multi threadingMulti threading
Multi threading
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
Greedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack ProblemGreedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack Problem
 
Operating System-Threads-Galvin
Operating System-Threads-GalvinOperating System-Threads-Galvin
Operating System-Threads-Galvin
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
 

Viewers also liked

Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.MOHIT DADU
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating SystemsRitu Ranjan Shrivastwa
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Ravindra Raju Kolahalam
 
Tutorial on Parallel Computing and Message Passing Model - C2
Tutorial on Parallel Computing and Message Passing Model - C2Tutorial on Parallel Computing and Message Passing Model - C2
Tutorial on Parallel Computing and Message Passing Model - C2Marcirio Chaves
 
Parallel architecture-programming
Parallel architecture-programmingParallel architecture-programming
Parallel architecture-programmingShaveta Banda
 
Intro to OpenMP
Intro to OpenMPIntro to OpenMP
Intro to OpenMPjbp4444
 
OpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersOpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersDhanashree Prasad
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel ProgrammingUday Sharma
 
Race condition
Race conditionRace condition
Race conditionhama7230
 
Parallel computing
Parallel computingParallel computing
Parallel computingvirend111
 
Semaphores OS Basics
Semaphores OS BasicsSemaphores OS Basics
Semaphores OS BasicsShijin Raj P
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process SynchronizationSonali Chauhan
 
Producer consumer
Producer consumerProducer consumer
Producer consumerMohd Tousif
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitorssgpraju
 
Ch7 OS
Ch7 OSCh7 OS
Ch7 OSC.U
 

Viewers also liked (20)

Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 
openmp
openmpopenmp
openmp
 
Tutorial on Parallel Computing and Message Passing Model - C2
Tutorial on Parallel Computing and Message Passing Model - C2Tutorial on Parallel Computing and Message Passing Model - C2
Tutorial on Parallel Computing and Message Passing Model - C2
 
Open mp intro_01
Open mp intro_01Open mp intro_01
Open mp intro_01
 
Openmp
OpenmpOpenmp
Openmp
 
Parallel architecture-programming
Parallel architecture-programmingParallel architecture-programming
Parallel architecture-programming
 
Intro to OpenMP
Intro to OpenMPIntro to OpenMP
Intro to OpenMP
 
OpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersOpenMP Tutorial for Beginners
OpenMP Tutorial for Beginners
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Race condition
Race conditionRace condition
Race condition
 
Parallel computing
Parallel computingParallel computing
Parallel computing
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Semaphores OS Basics
Semaphores OS BasicsSemaphores OS Basics
Semaphores OS Basics
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 
Producer consumer
Producer consumerProducer consumer
Producer consumer
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitors
 
Ch7 OS
Ch7 OSCh7 OS
Ch7 OS
 

More from Mohd Arif

Bootp and dhcp
Bootp and dhcpBootp and dhcp
Bootp and dhcpMohd Arif
 
Arp and rarp
Arp and rarpArp and rarp
Arp and rarpMohd Arif
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocolMohd Arif
 
Project identification
Project identificationProject identification
Project identificationMohd Arif
 
Project evalaution techniques
Project evalaution techniquesProject evalaution techniques
Project evalaution techniquesMohd Arif
 
Presentation
PresentationPresentation
PresentationMohd Arif
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Peer to-peer
Peer to-peerPeer to-peer
Peer to-peerMohd Arif
 
Overview of current communications systems
Overview of current communications systemsOverview of current communications systems
Overview of current communications systemsMohd Arif
 
Overall 23 11_2007_hdp
Overall 23 11_2007_hdpOverall 23 11_2007_hdp
Overall 23 11_2007_hdpMohd Arif
 
Objectives of budgeting
Objectives of budgetingObjectives of budgeting
Objectives of budgetingMohd Arif
 
Network management
Network managementNetwork management
Network managementMohd Arif
 
Networing basics
Networing basicsNetworing basics
Networing basicsMohd Arif
 
Iris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platformIris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platformMohd Arif
 
Ip sec and ssl
Ip sec and  sslIp sec and  ssl
Ip sec and sslMohd Arif
 
Ip security in i psec
Ip security in i psecIp security in i psec
Ip security in i psecMohd Arif
 
Intro to comp. hardware
Intro to comp. hardwareIntro to comp. hardware
Intro to comp. hardwareMohd Arif
 

More from Mohd Arif (20)

Bootp and dhcp
Bootp and dhcpBootp and dhcp
Bootp and dhcp
 
Arp and rarp
Arp and rarpArp and rarp
Arp and rarp
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocol
 
Project identification
Project identificationProject identification
Project identification
 
Project evalaution techniques
Project evalaution techniquesProject evalaution techniques
Project evalaution techniques
 
Presentation
PresentationPresentation
Presentation
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Peer to-peer
Peer to-peerPeer to-peer
Peer to-peer
 
Overview of current communications systems
Overview of current communications systemsOverview of current communications systems
Overview of current communications systems
 
Overall 23 11_2007_hdp
Overall 23 11_2007_hdpOverall 23 11_2007_hdp
Overall 23 11_2007_hdp
 
Objectives of budgeting
Objectives of budgetingObjectives of budgeting
Objectives of budgeting
 
Network management
Network managementNetwork management
Network management
 
Networing basics
Networing basicsNetworing basics
Networing basics
 
Loaders
LoadersLoaders
Loaders
 
Lists
ListsLists
Lists
 
Iris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platformIris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platform
 
Ip sec and ssl
Ip sec and  sslIp sec and  ssl
Ip sec and ssl
 
Ip security in i psec
Ip security in i psecIp security in i psec
Ip security in i psec
 
Intro to comp. hardware
Intro to comp. hardwareIntro to comp. hardware
Intro to comp. hardware
 
Heap sort
Heap sortHeap sort
Heap sort
 

Recently uploaded

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Recently uploaded (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Race conditions

  • 1. Catching Race Conditions An Extremely Difficult Task Statically detecting race conditions in a program using multiple semaphores is NP-hard. Thus, no efficient algorithms are available. We have to use human debugging skills. It is virtually impossible to catch race conditions dynamically because hardware must examine every memory access. So, we shall use a few examples to illustrate some subtle race conditions. 1
  • 2. Problem Statement Two groups, A and B, of processes exchange messages. Each process in A runs a function T_A(), and each process in B runs a function T_B(). Both T_A() and T_B() have an infinite loop and never stop. In the following, we show execution sequences that cause race conditions. You can always find a correct execution sequence without race conditions. 2
  • 3. Processes in group A Processes in group B T_A() T_B() { { while (1) { while (1) { // do something // do something Ex. Message Ex. Message // do something // do something } } } } 3
  • 4. What is Exchange Message? When a process in A makes a message available, it can continue only if it receives a message from a process in B who has successfully retrieves A’s message. Similarly, when a process in B makes a message available, it can continue only if it receives a message from a process in A who has successfully retrieves B’s message. How about exchanging business cards? 4
  • 5. Watch for Race Conditions • Suppose process A1 presents its message for B to retrieve. If A2 comes for message exchange before B retrieves A1’s, will A2’s message overwrites A1’s? • Suppose B has already retrieved A1’s message. Is it possible that when B presents its message, A2 picks it up rather than A1? • Thus, the messages between A and B must be well-protected to avoid race conditions. 5
  • 6. First Attempt sem A = 0, B = 0; I am ready int Buf_A, Buf_B; T_A() T_B() { { int V_a; int V_b; while (1) { while (1) { V_a = ..; V_b = ..; B.signal(); A.signal(); A.wait(); B.wait(); Buf_A = V_a; Buf_B = V_b; V_a = Buf_B; V_b = Buf_A; } } Wait for your card! 6
  • 7. First Attempt: Problem (a) Thread A Thread B B.signal() A.wait() A.signal() Buf_B has no value, yet! B.wait() Buf_A = V_a Oops, it is too late! V_a = Buf_B Buf_B = V_b 7
  • 8. First Attempt: Problem (b) A1 A2 B1 B2 B.signal() A.wait() A.signal() B.wait() B.signal() A.wait() Buf_B = . Race Condition A.signal() Buf_A = . Buf_A = . 8
  • 9. What did we learn? If there are shared data items, always protect them properly. Without a proper mutual exclusion, race conditions are likely to occur. In this first attempt, both global variables Buf_A and Buf_B are shared and should be protected. 9
  • 10. Second Attempt sem A = B = 0; sem Mutex = 1; int Buf_A, Buf_B; T_A() T_B() protection??? { int V_a; shake hands { int V_b; while (1) { while (1) { B.signal(); A.signal(); A.wait(); B.wait(); Mutex.wait(); Mutex.wait(); Buf_A = V_a; Buf_B = V_b; Mutex.signal(); Mutex.signal(); B.signal(); A.signal(); A.wait(); B.wait(); Mutex.wait(); Mutex.wait(); V_a = Buf_B; V_b = Buf_A; offer Mutex.signal(); Mutex.signal(); } My card } } } 10
  • 11. Second Attempt: Problem A1 A2 B B.signal() A.wait() A.signal() race condition B.wait() Buf_A = .. Buf_B = .. B.signal() hand shaking with A.wait() wrong person A.signal() B.wait() 11 Buf_A = ..
  • 12. What did we learn? Improper protection is no better than no protection, because it gives us an illusion that data have been well-protected. We frequently forgot that protection is done by a critical section, which cannot be divided. Thus, protecting “here is my card” followed by “may I have yours” separately is not good enough. 12
  • 13. Third Attempt sem Aready = Bready = 1; ready to proceed job done sem Adone = Bdone = 0; int Buf_A, Buf_B; T_A() T_B() { int V_a; { int V_b; while (1) { while (1) { only one A can Aready.wait(); Pass this point Bready.wait(); Buf_A = ..; Buf_B = ..; here is my card Adone.signal(); Bdone.signal(); let me have yours Bdone.wait(); Adone.wait(); V_a = Buf_B; V_b = Buf_A; Aready.signal(); Bready.signal(); } } } } 13
  • 14. Third Attempt: Problem Thread A Thread B Buf_A = Adone.signal() Bdone.wait() ruin the original Bdone.signal() value of Buf_A Adone.wait() … = Buf_B Aready.signal() B is a slow ** loop back ** thread Aready.wait() Buf_A = … race condition … = Buf_A 14
  • 15. What did we learn? Mutual exclusion for one group may not prevent processes in other groups from interacting with a process in this group. It is common that we protect a shared item for one group and forget other possible, unintended accesses. Protection must be applied uniformly to all processes rather than within groups. 15
  • 16. Fourth Attempt sem Aready = Bready = 1; ready to proceed job done sem Adone = Bdone = 0; int Buf_A, Buf_B; T_A() wait/signal T_B() { int V_a; switched { int V_b; while (1) { while (1) { I am the only A Bready.wait(); Aready.wait(); Buf_A = ..; Buf_B = ..; here is my card Adone.signal(); Bdone.signal(); waiting for yours Bdone.wait(); Adone.wait(); V_a = Buf_B; V_b = Buf_A; Job done & Aready.signal(); Bready.signal(); next B please } } } } 16
  • 17. Fourth Attempt: Problem A1 A2 B Bready.wait() Buf_A = … Adone.signal() Buf_B = … Bdone.signal() Adone.wait() … = Buf_A Bready.signal() Bready.wait() …… Hey, this one is for A1!!! Bdone.wait() … = Buf_B 17
  • 18. What did we learn? We use locks for mutual exclusion. The owner, the one who locked the lock, should unlock the lock. In the above “solution,” Aready is acquired by a process A but released by a process B. This is risky! In this case, a pure lock is more natural than a binary semaphore. 18
  • 19. Conclusions Detecting race conditions is difficult as it is an NP-hard problem. Hence, detecting race conditions is heuristic. Incorrect mutual exclusion is no better than no mutual exclusion. Race conditions are sometimes very subtle. They may appear at unexpected places. Check the ThreadMentor tutorial pages for more details and correct solutions. 19