Unobvious deadlock situation

Anton Litvinov :

Could you please explain why this deadlock happens ?

package main

import (
    "sync"
    "fmt"
    "runtime"
)

func main() {
    m := sync.RWMutex{}
    go func(){
        m.RLock()
        runtime.Gosched()
        m.RLock()
        m.RUnlock()
        m.RUnlock()
    }()

    runtime.Gosched()
    m.Lock()
    m.Unlock()

    fmt.Println("works")
}

It's non obvious to me why this deadlock always mostly happen. Could this be a quirk of the scheduler ?

n-canter :

From the RWMutex doc:

If a goroutine holds a RWMutex for reading and another goroutine might call Lock, no goroutine should expect to be able to acquire a read lock until the initial read lock is released. In particular, this prohibits recursive read locking. This is to ensure that the lock eventually becomes available; a blocked Lock call excludes new readers from acquiring the lock.

So what's going on in your code when deadlock occurs:

  1. first RLock()
  2. Lock() // this call waits until first Rlock() released and blocks calls to future Rlocks()
  3. Rlock() // this call waits until Lock() is released

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related