From 197ca0ea526e63fdda59da22b17c50ad6f2b2893 Mon Sep 17 00:00:00 2001 From: gjahn <gregor.jahn@bht-berlin.de> Date: Fri, 8 Dec 2023 00:21:44 +0100 Subject: [PATCH] Make ephemeral store concurrency-safe Fore more information see https://go.dev/blog/maps#concurrency --- state/ephemeral.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/state/ephemeral.go b/state/ephemeral.go index e01ac90..0d37040 100644 --- a/state/ephemeral.go +++ b/state/ephemeral.go @@ -2,17 +2,20 @@ package state import ( "errors" + "sync" ) type Ephemeral struct { - store map[ string ] *Item + store map[ string ] Item + mux sync.Mutex } func NewEphemeralStore() *Ephemeral { return &Ephemeral{ - store: map[ string ] *Item {}, + store: map[ string ] Item {}, + mux: sync.Mutex{}, } } @@ -23,7 +26,11 @@ func ( e *Ephemeral ) Add( i *Item ) error { } name := i.Name() + + e.mux.Lock() e.store[ name ] = i + e.mux.Unlock() + return nil } @@ -33,7 +40,10 @@ func ( e *Ephemeral ) Remove( name string ) error { return errors.New( "ephemeral storage not available" ) } + e.mux.Lock() delete( e.store, name ) + e.mux.Unlock() + return nil } @@ -43,7 +53,10 @@ func ( e *Ephemeral ) Fetch( name string ) ( *Item, error ) { return nil, errors.New( "ephemeral storage not available" ) } + e.mux.Lock() item, found := e.store[ name ] + e.mux.Unlock() + if !found { return nil, nil } @@ -56,10 +69,13 @@ func ( e *Ephemeral ) Show() ( []string, error ) { return nil, errors.New( "ephemeral storage not available" ) } + e.mux.Lock() names := make( []string, 0, len( e.store ) ) for k := range e.store { names = append( names, k ) } + e.mux.Unlock() + return names, nil } -- GitLab