You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import (
"sync"
)
// Define a struct that includes the map and a mutex.
type MapWithMutex struct {
m map[string]int
mu sync.Mutex
}
func main() {
// Create an instance of MapWithMutex.
mwm := MapWithMutex{
m: make(map[string]int),
}
// Create and start multiple goroutines.
for i := 0; i < 10; i++ {
go func(i int) {
key := strconv.Itoa(i)
// Lock the mutex before accessing the map.
mwm.mu.Lock()
defer mwm.mu.Unlock()
// Perform read or write operations on the map.
mwm.m[key] = i
value := mwm.m[key]
fmt.Printf("Goroutine %d: Key %s, Value %d\n", i, key, value)
}(i)
}
// Wait for the goroutines to finish.
time.Sleep(time.Second)
}
The text was updated successfully, but these errors were encountered: