Skip to content

Instantly share code, notes, and snippets.

@manjeettahkur
Created January 11, 2023 08:25
Show Gist options
  • Save manjeettahkur/89a0a6f5f8af68950dcefe777eb3c3f4 to your computer and use it in GitHub Desktop.
Save manjeettahkur/89a0a6f5f8af68950dcefe777eb3c3f4 to your computer and use it in GitHub Desktop.
Which snippet of code acquire more locks
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var mu sync.Mutex
// A
go (func() {
var count int
n := time.Now()
for time.Since(n) < time.Second {
mu.Lock()
time.Sleep(2 * time.Nanosecond)
mu.Unlock()
count++
}
fmt.Println("Acquired lock", count)
})()
// B
go (func() {
var count int
n := time.Now()
for time.Since(n) < time.Second {
mu.Lock()
time.Sleep(time.Nanosecond)
mu.Unlock()
mu.Lock()
time.Sleep(time.Nanosecond)
mu.Unlock()
count++
}
fmt.Println("acquired lock", count)
})()
time.Sleep(4*time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment