Skip to content

Commit 7c44ec1

Browse files
committed
Add critical-section-and-synchronization.md
1 parent 0e0fde5 commit 7c44ec1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Critical Section and Synchronization
2+
3+
A critical section is a section of code that needs to be executed without outside interference - i.e. without another thread potentially affecting/being affected by "intermediate" states within the section.
4+
5+
For instance, a reservation system might have a critical section when reserving something in that it needs to both check to see if the item is available and then mark it as no longer available, without some other attempt at reserving the room changing that status in the middle.
6+
7+
Thus, the critical section of a piece of code is a **place where only one thread of execution is allowed to be at a time**, to prevent things like _race conditions_.
8+
9+
> A critical section wraps that portion of your code where shared data is being modified.
10+
11+
12+
## Two Types of Race Conditions
13+
14+
Race conditions can occur when two or more threads read and write the same variable according to one of these two patterns:
15+
16+
- **Read-modify-write**
17+
- **Check-then-act**
18+
19+
20+
## Read-Modify-Write Critical Sections
21+
22+
The **read-modify-write** pattern means, that two or more threads first read a given variable, then modify its value and write it back to the variable.
23+
For this to cause a problem, the new value must depend one way or another on the previous value.
24+
The problem that can occur is, if two threads read the value (into CPU registers) then modify the value (in the CPU registers) and then write the values back.
25+
26+
```java
27+
public class Counter {
28+
protected long count = 0;
29+
30+
public void add(long value) {
31+
this.count = this.count + value;
32+
}
33+
}
34+
```

0 commit comments

Comments
 (0)