DEV Community

ivinieon
ivinieon

Posted on • Edited on

Synchronization, Race Condition, Critical Section

What happens when two threads access one object?

→ Why is synchronization important?

java
Copy code
for(apple for appleBox) {
    if(apple status is bad) {
        badCounter.increment(); 
    }
}

public class Counter {
    private int state = 0;
    public void increment() {state++;}
//1. LOAD state to R1 // Load state into R1
//2. R1 = R1 + 1 // Add 1 to R1 and store the result in R1
//3. STORE R1 to state // Store R1 back into state
    public int get() {return state;}
}
Enter fullscreen mode Exit fullscreen mode

Assuming that two threads check for bad apples in one appleBox respectively using this code, if T1 finds 2 bad apples and T2 finds 5 bad apples, the value of memory's state, which is initially 0, is expected to be 7, but that's not always the case.

The result can be different depending on when the context switching occurs.

For example, when T1 loads the state from memory to R1, R1 becomes 0. Then, when T1 stores the result of adding 1 to R1 in R1, R1 becomes 1. If a context switching occurs at this point, T2 executes steps 1 and 2, and stores the value of R1 in memory's state. Then, when context switching occurs again and T1 stores R1 in state, the value remains 1 because T2 already stored it as 1. (It should have been 2 originally.)
→Race condition

Race condition: A situation where the result may vary depending on the timing or access order when multiple processes/threads manipulate the same data.

Synchronization: Maintaining the consistency of shared data even when multiple processes/threads are executed simultaneously.

How to synchronize?

Critical section: An area that only one process/thread can enter and execute to ensure the consistency of shared data.

java
Copy code
do{
    entry section
        critical section
    exit section
        reminder section
} while(TRUE)
Enter fullscreen mode Exit fullscreen mode

Conditions for solving the critical section problem

1. Mutual exclusion
→ Only one process/thread can execute the critical section at a time.

2. Progress
→ If the critical section is empty and multiple processes/threads want to enter the critical section, one of them must be executed.

3. Bounded waiting
→ Waiting indefinitely to enter the critical section should not be allowed.

This posting is just a study note which was written after watching youtube videos in Korean.

Youtube Link

Top comments (0)