golang-lru
golang-lru copied to clipboard
Suggestion to handle thread safe for LRU Cache
This LRU cache is not a thread safe. So it's better to add a thread safe layer to this.
Code to reproduce the concurrent access.
Code :-
// github.com/hashicorp/golang-lru/simplelru package main
import ( "log" "sync"
"github.com/hashicorp/golang-lru/simplelru"
)
var wg sync.WaitGroup
func main() { LRU, err := simplelru.NewLRU(100, nil) if err != nil { log.Fatal(err) return } for i := 0; i < 100; i++ { LRU.Add(100, 100) } wg.Add(2) go FreqAccess(LRU) go FreqWrite(LRU) wg.Wait() }
func FreqAccess(lru *simplelru.LRU) { defer wg.Done() for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() lru.Get(i) }() } } func FreqWrite(lru *simplelru.LRU) { defer wg.Done() for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() lru.Add(i, i) }() } }
Error :-
fatal error: concurrent map read and map write
You're using simplelru
which states it's not thread-safe. Here is a playground using the golang-lru
https://go.dev/play/p/19tko_0e-cN
You're using
simplelru
which states it's not thread-safe. Here is a playground using thegolang-lru
https://go.dev/play/p/19tko_0e-cN
run code fail
You're using
simplelru
which states it's not thread-safe. Here is a playground using thegolang-lru
https://go.dev/play/p/19tko_0e-cNrun code fail
https://go.dev/play/p/cQTQUTwehFs
Thanks, @maple-j - your link shows the code working