头图

background

Google engineer Valentin Deleplace came up with 2 questions about locks and shared them with you.

Topic 1

// quiz_lock1.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    var m sync.Mutex
    fmt.Print("1, ")
    m.Lock()
    m.Lock()
    m.Unlock()
    fmt.Println("2")
}
  • A: 1, 2
  • B: 1,
  • C: 1, fatal error:......
  • D: compile error

Topic 2

// quiz_lock2.go
package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var m sync.Mutex
    fmt.Print("1, ")
    m.Lock()

    go func() {
        time.Sleep(200 * time.Millisecond)
        m.Unlock()
    }()

    m.Lock()
    fmt.Println("2")
}
  • A: 1, 2
  • B: 1,
  • C: 1, fatal error:......
  • D: compile error

Parse

Both sync.Mutex and sync.RWMutex in Go language are not reentrant, and there is no reentrant lock (also called recursive lock) in Go language.

If the mutex is not released, the same goroutine cannot lock the mutex twice, otherwise the second lock will block. If there is no other goroutine to release the mutex, it will cause a deadlock and a runtime error: fatal error: all goroutines are asleep - deadlock! will appear.

At the same time, sync.Mutex and sync.RWMutex allow one goroutine to lock it and other goroutines to unlock it, and do not require locking and unlocking in the same goroutine.

So the answer to the first question is C and the answer to the second question is A .

thinking questions

// quiz_lock3.go

package main

import (
    "fmt"
    "sync"
)

var a sync.Mutex

func main() {
    a.Lock()
    fmt.Print("1, ")
    a.Unlock()
    fmt.Print("2, ")
    a.Unlock()
    fmt.Println("3")
}
  • A: 1, 2, 3
  • B: 1, 2, fatal error:......
  • C: 1, 2
  • D: compile error

If you want to know the answer, you can send a message to the official account at mutex to get the answer.

Summarize

The locks in Go language are different from those in C++ and Java. We summarize the following precautions for you

  • Go's locks are not reentrant, there are no recursive locks
  • Allow one goroutine to lock and another goroutine to unlock, without requiring locking and unlocking in the same goroutine
  • The zero value of sync.Mutex is an unlocked Mutex, and the zero value of sync.RWMutex is an unlocked RWMutex
  • For more details, please refer to the official description of Mutex and RWMutex in References

open source address

The article and sample code are open sourced on GitHub: Go language beginner, intermediate and advanced tutorial .

Official account: coding advanced. Follow the official account to get the latest Go interview questions and technology stacks.

Personal website: Jincheng's Blog .

Know: Wuji .

References


coding进阶
116 声望18 粉丝