Skip to content

Instantly share code, notes, and snippets.

@Gabriella439
Created December 3, 2020 23:27
Show Gist options
  • Save Gabriella439/8d2428c725923981866c3b343166b967 to your computer and use it in GitHub Desktop.
Save Gabriella439/8d2428c725923981866c3b343166b967 to your computer and use it in GitHub Desktop.
Low-tech concurrent hashmap
module ConcurrentMap where
import Control.Concurrent.STM.TVar (TVar)
import Control.Concurrent.STM (STM)
import Data.Hashable (Hashable)
import Data.HashMap.Strict (HashMap)
import Data.Vector (Vector)
import qualified Control.Concurrent.STM.TVar as TVar
import qualified Data.Hashable as Hashable
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Vector as Vector
newtype Map k v = Map { unMap :: Vector (TVar (HashMap k v)) }
new :: Int -> STM (Map k v)
new n = do
vector <- Vector.replicateM (2^n) (TVar.newTVar HashMap.empty)
return (Map vector)
insert :: (Eq k, Hashable k) => k -> v -> Map k v -> STM ()
insert key value (Map vector) = do
let index = Hashable.hash key `rem` Vector.length vector
TVar.modifyTVar' (Vector.unsafeIndex vector index) (HashMap.insert key value)
lookup :: (Eq k, Hashable k) => k -> Map k v -> STM (Maybe v)
lookup key (Map vector) = do
let index = Hashable.hash key `rem` Vector.length vector
m <- TVar.readTVar (Vector.unsafeIndex vector index)
return (HashMap.lookup key m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment