Let’s Go:3-Concurrency1
Go Study Part 3 - Concurrency1
Notifier: This series is based on the book Go in Action& Concurrency in Go: Tools and Techniques for Developers.
Concurrent code is notoriously difficult to get right.
-
Race conditions
A race condition occurs when two or more operations must execute in the correct order, but the program has not been written so that this order is guaranteed to be maintained. -
Atomicity When something is considered atomic, or to have the property of atomicity, this means that within the context that it is operating, it is indivisible, or uninterruptible. So, if something is atomic, it is safe within concurrent contesxts implicitly.
- Memory Access Synchronization
var data int go func() { data++}()// critical section 1 if data == 0 {// critical section 2 fmt.Println("the value is 0.") } // critical section 3 else { fmt.Printf("the value is %v.\n", data) }
sync.mutex ype is used to synchronize access to a shared resource.
- Deadlocks, Livelocks, and Starvation
a. Deadlock : A deadlocked program is one in which all concurrent processes are waiting on one another. In this state, the program will never recover without outside intervention.
type value struct {
mu sync.Mutex
value int
}
var wg sync.WaitGroup
printSum := func(v1, v2 *value) {
defer wg.Done()
v1.mu.Lock()
defer v1.mu.Unlock()
time.Sleep(2*time.Second)
v2.mu.Lock()
defer v2.mu.Unlock()
fmt.Printf("sum=%v\n", v1.value + v2.value)
}
var a, b value
wg.Add(2)
go printSum(&a, &b)
go printSum(&b, &a)
wg.Wait()
Code above can be illustrated as below:
As you can see, first printSum is waiting for the second printSum to finish. And the second printSum is waiting for the first printSum to finish. Therefore, both goruoutines are waiting for each other forever.And also, you can see race condition between first and second goroutines.
b. Livelock: Livelocks are programs that are actively performing concurrent operations, but these operations do nothing to move the state of the program forward.
c. Starvation: Starvation is when a program is waiting for a resource that is not available.