To implement a concurrent-safe data cache in Go, you can use the sync package from the Go standard library. Here's an example implementation:
type DataCache struct {
data map[string]interface{}
mutex sync.RWMutex
}
Create methods to perform operations on the cache. Some common methods are:
Get(key string) (interface{}, bool)
: Retrieves the data for the given key from the cache.Set(key string, value interface{})
: Stores the given value in the cache for the specified key.Delete(key string)
: Removes the specified key and its associated value from the cache.Clear()
: Clears the entire cache.func (c *DataCache) Get(key string) (interface{}, bool) {
c.mutex.RLock()
defer c.mutex.RUnlock()
value, ok := c.data[key]
return value, ok
}
func (c *DataCache) Set(key string, value interface{}) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.data[key] = value
}
func (c *DataCache) Delete(key string) {
c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.data, key)
}
func (c *DataCache) Clear() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.data = make(map[string]interface{})
}
func main() {
cache := &DataCache{
data: make(map[string]interface{}),
}
// Access the cache concurrently
go func() {
cache.Set("key1", "value1")
value, ok := cache.Get("key1")
// ...
}()
go func() {
value, ok := cache.Get("key1")
// ...
cache.Delete("key1")
// ...
}()
// ...
}
By using a sync.RWMutex
, the cache allows multiple readers to access data concurrently while ensuring exclusive access during write operations.