Safe concurrent read and write in maps

https://play.golang.org/p/9QjRxat17CU
Trying to make a program that reads and writes to a map safely. Im still a bit new, so im not sure if my program is good, or if its good, how can i be improved
https://play.golang.org/p/9QjRxat17CU

I create a struct that encapsulate mutes and map, so it would be clear their relationship

type MyMap struct {
	sync.RWMutex
	internal map[string]int
}

func (m *MyMap) read(key string) (int, boolean) {
	m.RLock()
	result, ok := m.internal[key]
	m.RUnlock()
	return result, ok
}

func (m *MyMap) write(key string, value int) {
	m.Lock()
	m.internal[key] = value
	m.Unlock()
}
1 Like

Could you please show how it’s implemented in the main function? Like a writing and reading example

  1. Change the map declaration to
var m *MyMap
  1. Inits m in your main function
m = &MyMap{
		internal: map[string]int{
			"justin": 19,
			"james":  28,
			"juliet": 20,
		},
	}

3 ) Change read and write goroutines to

func read() {
  if r, ok := m.read("justin"); ok {
      fmt.Println(r)
  }
}

func write() {
  m.write("justin", 20)
  fmt.Println(m.internal)
}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.