Created
January 11, 2023 08:25
-
-
Save manjeettahkur/89a0a6f5f8af68950dcefe777eb3c3f4 to your computer and use it in GitHub Desktop.
Which snippet of code acquire more locks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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