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

Network security Lab manual
Network security Lab manual Network security Lab manual
Network security Lab manual Vivek Kumar Sinha
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingC4Media
 
OWASP AppSecCali 2015 - Marshalling Pickles
OWASP AppSecCali 2015 - Marshalling PicklesOWASP AppSecCali 2015 - Marshalling Pickles
OWASP AppSecCali 2015 - Marshalling PicklesChristopher Frohoff
 
Session hijacking by rahul tyagi
Session hijacking by rahul tyagiSession hijacking by rahul tyagi
Session hijacking by rahul tyagiamansyal
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++Arpita Patel
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithmAamir Sohail
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Secure software development presentation
Secure software development presentationSecure software development presentation
Secure software development presentationMahdi Dolati
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Automata theory
Automata theoryAutomata theory
Automata theorycolleges
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handlingNahian Ahmed
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applicationsAdeel Javaid
 

What's hot (20)

Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Local File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code ExecutionLocal File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code Execution
 
Hash tables
Hash tablesHash tables
Hash tables
 
Network security Lab manual
Network security Lab manual Network security Lab manual
Network security Lab manual
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
OWASP AppSecCali 2015 - Marshalling Pickles
OWASP AppSecCali 2015 - Marshalling PicklesOWASP AppSecCali 2015 - Marshalling Pickles
OWASP AppSecCali 2015 - Marshalling Pickles
 
Xss ppt
Xss pptXss ppt
Xss ppt
 
Session hijacking by rahul tyagi
Session hijacking by rahul tyagiSession hijacking by rahul tyagi
Session hijacking by rahul tyagi
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithm
 
Java package
Java packageJava package
Java package
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
Secure software development presentation
Secure software development presentationSecure software development presentation
Secure software development presentation
 
Red black tree
Red black treeRed black tree
Red black tree
 
Automata theory
Automata theoryAutomata theory
Automata theory
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
 

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

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

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