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 (20)

deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidance
 
Address Binding Scheme
Address Binding SchemeAddress Binding Scheme
Address Binding Scheme
 
Boyer more algorithm
Boyer more algorithmBoyer more algorithm
Boyer more algorithm
 
Leftist heap
Leftist heapLeftist heap
Leftist heap
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocks
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Semaphores
SemaphoresSemaphores
Semaphores
 
Frequent itemset mining methods
Frequent itemset mining methodsFrequent itemset mining methods
Frequent itemset mining methods
 
Time space trade off
Time space trade offTime space trade off
Time space trade off
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Unix ch03-03(2)
Unix ch03-03(2)Unix ch03-03(2)
Unix ch03-03(2)
 
Singly Linked List & Data Structure
Singly Linked List & Data StructureSingly Linked List & Data Structure
Singly Linked List & Data Structure
 
Pthread
PthreadPthread
Pthread
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
System calls
System callsSystem calls
System calls
 

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
 

Viewers also liked (20)

Race condition
Race conditionRace condition
Race condition
 
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
 

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

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
🐬 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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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