Sobes.tech
Senior

Are there still data races in the implementation? Specifically in the Keys method that returns a slice of keys?

sobes.tech AI

Answer from AI

If the Keys method returns a slice of keys from a structure that can be modified concurrently, data races are possible if synchronization is not used.

For example, if you have a map and the Keys method iterates over its keys, while another goroutine modifies the map, it will lead to a data race and panic.

To avoid data races:

  • Use mutexes (sync.Mutex) to protect access to the structure during read and write.
  • You can make a copy of the keys under mutex protection and return it.

Example:

func (c *Cache) Keys() []string {
    c.mu.Lock()
    defer c.mu.Unlock()
    keys := make([]string, 0, len(c.data))
    for k := range c.data {
        keys = append(keys, k)
    }
    return keys
}

Without such protection, data races are possible.

If the Keys method returns a reference to an internal slice or structure that can be modified, races are also possible. Always copy data or synchronize access.

Are there still data races in the implementation… - sobes.tech