Because of the company arrangement, I temporarily moved from the Java project team to the Go Project team, after almost 5 days of spare time to go to study, the architect let me to the company colleagues Golang sharing and training.
Colleagues were very passionate about technology, and were expected to share it for 40 minutes, which lasted 2 hours, thanks to the active discussion of colleagues and the enthusiastic addition of colleagues from the go big guy. I recorded a few of the important points of the discussion in this sharing, so that we could get to the point of the go and avoid the pit.
The Dealock in Go are divided into two main categories:
1. Channel-related deadlocks
Read and write nil channel, resulting in deadlock
func main() { ch := make(chan int) ch <- 1 }
goroutine 1 [chan send]:
Image.png
2. Textbook type of deadlock
This is the deadlock in the operating system textbook, waiting for each other to release the lock.
var lock1 *sync.Mutexvar lock2 *sync.Mutexfunc main() { lock1 = new(sync.Mutex) lock2 = new(sync.Mutex) go func() { lock1.Lock() fmt.Println("I'm a goroutine,I have lock1,and I need lock2.") time.Sleep(time.Second) lock2.Lock() lock2.Unlock() lock1.Unlock() }() lock2.Lock() fmt.Println("I'm the main goroutine,I have lock2,and I need lock1.") time.Sleep(time.Second) lock1.Lock() lock1.Unlock() lock2.Unlock() time.Sleep(5 * time.Second)}
goroutine 1 [semacquire]:
Image.png
Easy wrong point
Q: If the only Mian Goroutine is blocked, it will cause a deadlock.
A: No, only the blocking caused by the nil channel will cause a deadlock. Blocking caused by other causes does not cause deadlocks, as in the following example.
func main() { log.Fatal(http.ListenAndServe(":8000", nil)) //block log.Print("This doesn't print") fmt.Println("Can't reach here.")}
Q: When the GO runtime retrieves the deadlock
A: When 所有
the goroutine is not accessible, go runtime detects the situation and throws deadlock. (TODO, this is not a perfect conclusion)
More examples of deadlock: Https://gitee.com/sicnu-yudidi/go/tree/master/go-3/deadlock
Https://programming.guide/go/detect-deadlock.html
Https://stackoverflow.com/questions/42432880/why-does-this-goroutine-block