Concurrency in Go Chapter1 (5)

“Concurrency in Go: Tools and Techniques for Developers”の1章 “An Introduction to Concurrency”の読書メモ。Deadlockについて書く。

Deadlock

package mainimport (
"fmt"
"sync"
"time"
)
func main() {
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()
}

Deadlockは以下の4つの状態(Coffman conditions)を満たす時に発生しうる。

Mutufal Exclusion

Wait For Condition

No Preemption

Circular Wait

--

--

Software engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store