golang-lru icon indicating copy to clipboard operation
golang-lru copied to clipboard

Suggestion to handle thread safe for LRU Cache

Open nagnagendra opened this issue 2 years ago • 1 comments

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

nagnagendra avatar Jun 27 '22 10:06 nagnagendra

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

SamHennessy avatar Aug 14 '22 04:08 SamHennessy

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

run code fail image

TeqGin avatar Mar 07 '23 05:03 TeqGin

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

run code fail image

https://go.dev/play/p/cQTQUTwehFs

maple-j avatar Sep 14 '23 17:09 maple-j

Thanks, @maple-j - your link shows the code working

mgaffney avatar Sep 21 '23 19:09 mgaffney