From 3956adab006f39888d12cdae917c067cc2d8ad6a Mon Sep 17 00:00:00 2001 From: "Scott R. Parish" Date: Sat, 13 Mar 2010 20:46:57 -0600 Subject: [PATCH] create global oigInc instance Before if multiple threads instantiated their own ObjectIdGen structure it would be possible to get duplicate objectid's generated. By making sure there is a single inc counter, this is avoided. --- Database/MongoDB/BSON.hs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Database/MongoDB/BSON.hs b/Database/MongoDB/BSON.hs index 62cf41d..d51bcb9 100644 --- a/Database/MongoDB/BSON.hs +++ b/Database/MongoDB/BSON.hs @@ -37,7 +37,7 @@ module Database.MongoDB.BSON -- * Binary encoding/decoding getBsonDoc, putBsonDoc, -- * ObjectId creation - mkObjectIdGen, genObjectId, + ObjectIdGen, mkObjectIdGen, genObjectId, ) where import Prelude hiding (lookup) @@ -64,6 +64,7 @@ import Data.Typeable import Database.MongoDB.Util import Network.BSD import Numeric +import System.IO.Unsafe import System.Posix.Process -- | BsonValue is the type that can be used as a key in a 'BsonDoc'. @@ -150,12 +151,15 @@ data ObjectIdGen = ObjectIdGen { oigInc :: IORef Integer } +globalObjectIdInc :: IORef Integer +{-# NOINLINE globalObjectIdInc #-} +globalObjectIdInc = unsafePerformIO (newIORef 0) + mkObjectIdGen :: IO ObjectIdGen mkObjectIdGen = do host <- liftM (fst . (!! 0) . readHex . List.take 6 . md5sum . C8.pack) getHostName - inc <- newIORef 0 - return ObjectIdGen {oigMachine = host, oigInc = inc} + return ObjectIdGen {oigMachine = host, oigInc = globalObjectIdInc} genObjectId :: ObjectIdGen -> IO BsonValue genObjectId oig = do