I guess the problem with this implementation is it requires a last reader for every write. If there are always readers, the second Update will block.
// infogulch's lock-free implementation of WRRMMap template <class K, class V> class WRRMMap { Map<K, V>* pMap_, * pGC_; unsigned readers; public: V Lookup (const K& k) { unsigned r while (r = readers, !CAS(&readers, r, r+1)); // increment readers V ret = (*pMap_) [k]; while (r = readers, !CAS(&readers, r, r-1)); // decrement if (r == 1 && pGC_) { // last reader. garbage collect delete pGC_; pGC_ = 0; } return ret; } void Update(const K& k, const V& v) { Map<K, V>* pNew = 0, * pOld; do { pOld = pMap_; delete pNew; pNew = new Map<K, V>(*pOld); (*pNew) [k] = v; } while (!CAS(&pMap_, pOld, pNew)); // DON'T delete pMap_; // wait for the GC spot to be open, set it while (!CAS(&pGC_, 0, pOld)); } };
I guess the problem with this implementation is it requires a last reader for every write. If there are always readers, the second Update will block.
(Meta question: ok to put this much code here?)