You've already forked go-profiler-notes
mirror of
https://github.com/DataDog/go-profiler-notes.git
synced 2025-07-15 23:54:16 +02:00
add stuck examples
This commit is contained in:
3
examples/stuck-deadlock/go.mod
Normal file
3
examples/stuck-deadlock/go.mod
Normal file
@ -0,0 +1,3 @@
|
||||
module github.com/felixge/go-profiler-notes/examples/stuck-program
|
||||
|
||||
go 1.15
|
48
examples/stuck-deadlock/main.go
Normal file
48
examples/stuck-deadlock/main.go
Normal file
@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
var (
|
||||
a = &sync.Mutex{}
|
||||
b = &sync.Mutex{}
|
||||
)
|
||||
go bob(a, b)
|
||||
go alice(a, b)
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
<-c
|
||||
return nil
|
||||
}
|
||||
|
||||
func bob(a, b *sync.Mutex) {
|
||||
for {
|
||||
fmt.Println("bob is okay")
|
||||
a.Lock()
|
||||
b.Lock()
|
||||
a.Unlock()
|
||||
b.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func alice(a, b *sync.Mutex) {
|
||||
for {
|
||||
fmt.Println("alice is okay")
|
||||
b.Lock()
|
||||
a.Lock()
|
||||
b.Unlock()
|
||||
a.Unlock()
|
||||
}
|
||||
}
|
3
examples/stuck-producer-worker/go.mod
Normal file
3
examples/stuck-producer-worker/go.mod
Normal file
@ -0,0 +1,3 @@
|
||||
module github.com/felixge/go-profiler-notes/examples/stuck-program
|
||||
|
||||
go 1.15
|
54
examples/stuck-producer-worker/main.go
Normal file
54
examples/stuck-producer-worker/main.go
Normal file
@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
workCh := make(chan int)
|
||||
go worker(workCh)
|
||||
go producer(workCh)
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
<-c
|
||||
return nil
|
||||
}
|
||||
|
||||
func producer(workCh chan<- int) {
|
||||
for msg := 0; ; msg++ {
|
||||
workCh <- msg
|
||||
fmt.Printf("producer sent: %d\n", msg)
|
||||
if rand.Int63n(10) == 0 {
|
||||
takeNap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func worker(workCh <-chan int) {
|
||||
for {
|
||||
msg := <-workCh
|
||||
fmt.Printf("worker received: %d\n", msg)
|
||||
if rand.Int63n(10) == 0 {
|
||||
takeNap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func takeNap() {
|
||||
var forever chan struct{}
|
||||
<-forever
|
||||
}
|
Reference in New Issue
Block a user