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

17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMS
koolkampus
 
Free space managment46
Free space managment46Free space managment46
Free space managment46
myrajendra
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
MYER301
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
Sukrit Gupta
 

What's hot (20)

Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentals
 
Hash table
Hash tableHash table
Hash table
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Lossless decomposition
Lossless decompositionLossless decomposition
Lossless decomposition
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMS
 
Free space managment46
Free space managment46Free space managment46
Free space managment46
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
Dead Lock in operating system
Dead Lock in operating systemDead Lock in operating system
Dead Lock in operating system
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating System
 
Linux security
Linux securityLinux security
Linux security
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Translation Look Aside buffer
Translation Look Aside buffer Translation Look Aside buffer
Translation Look Aside buffer
 
System calls
System callsSystem calls
System calls
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Chapter 11 - File System Implementation
Chapter 11 - File System ImplementationChapter 11 - File System Implementation
Chapter 11 - File System Implementation
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 

Viewers also liked

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 - C2
Marcirio Chaves
 
Parallel architecture-programming
Parallel architecture-programmingParallel architecture-programming
Parallel architecture-programming
Shaveta Banda
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
Uday Sharma
 
Parallel computing
Parallel computingParallel computing
Parallel computing
virend111
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
Sonali Chauhan
 
Ch7 OS
Ch7 OSCh7 OS
Ch7 OS
C.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 dhcp
Mohd Arif
 
Arp and rarp
Arp and rarpArp and rarp
Arp and rarp
Mohd Arif
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocol
Mohd Arif
 
Project identification
Project identificationProject identification
Project identification
Mohd Arif
 
Project evalaution techniques
Project evalaution techniquesProject evalaution techniques
Project evalaution techniques
Mohd Arif
 
Presentation
PresentationPresentation
Presentation
Mohd Arif
 
Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 
Peer to-peer
Peer to-peerPeer to-peer
Peer to-peer
Mohd Arif
 
Overview of current communications systems
Overview of current communications systemsOverview of current communications systems
Overview of current communications systems
Mohd Arif
 
Overall 23 11_2007_hdp
Overall 23 11_2007_hdpOverall 23 11_2007_hdp
Overall 23 11_2007_hdp
Mohd Arif
 
Objectives of budgeting
Objectives of budgetingObjectives of budgeting
Objectives of budgeting
Mohd Arif
 
Network management
Network managementNetwork management
Network management
Mohd Arif
 
Networing basics
Networing basicsNetworing basics
Networing basics
Mohd 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 platform
Mohd Arif
 
Ip sec and ssl
Ip sec and  sslIp sec and  ssl
Ip sec and ssl
Mohd Arif
 
Ip security in i psec
Ip security in i psecIp security in i psec
Ip security in i psec
Mohd Arif
 
Intro to comp. hardware
Intro to comp. hardwareIntro to comp. hardware
Intro to comp. hardware
Mohd 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

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 

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