lock free - LockFree MultiConsumer/MultiProducer Queue -


i've written simple lock-free single-consumer/-producer queue. it's supposed work this:

  • at time many consumers may read it
  • at time multiple producers can write it, added elements made available later
  • after write modification finished, call "makepushedelementsavailable()", consumers can read newly added elements

.

template<typename t, int size> class mcmpqueue { public:     mcmpqueue();     bool trypushlater(const t &element);     bool trypop(t &element);     void makepushedelementsavailable(); protected: private:     t elements[size];     std::atomic<int> ihead, itail, iwrite; };  template<typename t, int size> mcmpqueue<t, size>::scmpqueue() : ihead(0), itail(0), iwrite(0) { }  template<typename t, int size> void mcmpqueue<t, size>::makepushedelementsavailable() {     itail.store(iwrite.load()); }  template<typename t, int size> bool mcmpqueue<t, size>::trypop(t &element) {     int newindex;     int index;     {         index = ihead.load();         if (index == itail.load())             return false;         newindex = index + 1;     } while (!ihead.compare_exchange_weak(index, newindex));      index = index % size;     element = elements[index];     return true; }  template<typename t, int size> bool mcmpqueue<t, size>::trypushlater(const t &element) {     int newindex;     int index;     {         index = iwrite.load();         if (index - ihead.load() >= size)             return false;         newindex = index + 1;     } while (!iwrite.compare_exchange_weak(index, newindex));      index = index % size;     elements[index] = element;     return true; } 

so far seems work fine, i'd have checked others though please. there simpler way making elements available after updating has finished?

thanks.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -