Mutex lock for write only
I have a multithreaded C ++ application that contains a complex data structure in memory (cached data).
Everything is fine when I just read the data. I can have as many threads as I want to receive data.
However, the cached structure is not static.
- If the requested data item is not available, it will be read from the database and then inserted into the data tree. This is probably not a problem either, and even if I use a mutex when I add a new data item to the tree, it only takes a few cycles (just by adding a pointer).
- There is a garbage collection process that runs from time to time. It removes all old items from the tree. To do this, I need to block the whole thing to make sure that no other process has access to any data that will be removed from memory. I also need to lock the tree while I am reading from the cache so that I don't delete items while they are being processed (something like "same thing differently").
"pseudocode":
function getItem(key)
lockMutex()
foundItem = walkTreeToFindItem(key)
copyItem(foundItem, safeCopy)
unlockMutex()
return safeCopy
end function
function garbageCollection()
while item = nextItemInTree
if (tooOld) then
lockMutex()
deleteItem(item)
unlockMutex()
end if
end while
end function
What worries me: it means I have to lock the tree while reading (to avoid garbage collection to start when I read). However - as a side effect - I also cannot have two reading processes at the same time.
Any suggestions?
Is there some kind of "this read-only action that only collides with the record" Mutex?
source to share
Have a look at read-write-lock .
You haven't specified what framework you can use, but pThread and boost have implemented this pattern.
source to share
The concept is "co-reader, single writer," as others have stated. In Linux environments, you can use pthread_rwlock_t
without any frameworks. I would suggest looking into the boost::shared_lock
.
source to share
I suggest a read-write lock . The idea is that you can acquire a "read" or "write" lock, and the lock will allow multiple readers, but only one author. Very comfortably.
source to share