golang mutexes aren't recursive / re-entrant

golang mutex are a lot different from C# locks. In C#, locking on an object will check whether the current thread has already locked on the object or not. If it has, the locking is successful. However in golang, each mutex.Lock() attempts to lock regardless whether goroutine has already been locked or not.


package main

import "fmt"
import "sync"
import "time"

func main() {
go func(){
var mu sync.Mutex
fmt.Println("first lock")
fmt.Println("2nd lock")
fmt.Println("exiting goroutine")

time.Sleep(5*time.Second) // wait 5 seconds

In the above program, the 2nd lock call will deadlock as it waits for the lock to be released.

© 2018 Nirandas Thavorath. All Rights Reserved.
Last updated at Tuesday January 17, 2017 06:48 AM