Some time ago I read about the lock-free map implementation technology, mainly using CAS, FAA and so on.
If you do not know CAS and FAA, you can go to Baidu. CAS and FAA are more efficient than locks because they use the CPU features and do not need to consider the memory context during switching.
Here we come up with a non-lock map implementation idea. We can inherit the map from STL and encapsulate it by ourselves. The CAS technology is used to implement the lock mechanism and insert the encapsulated map, delete and other operations are synchronized using the lock mechanism implemented by CAS.
Due to my use of vs2008, stl cas implementation cannot be provided (cross-platform). Now, implementation in Windows is provided.
# Include "windows. H "class caslock {const long klockedflag _ = 1; const long kunlockflag _ = 0; void lock () {While (true) {If (interlockedcompareexchange (Lock _, klockedflag __, kunlockflag _) = kunlockflag _) {break;} Sleep (1) ;}} void unlock () {lock _ = kunlockflag __;} PRIVATE: // The value of lock _ 1 indicates that someone occupies the lock. The value of lock_1 0 indicates that volatile long lock _;} is not preemptible currently _;};
Of course, the above is just a simple implementation. If you need to do a lock-free queue and you need to consider other issues, we will not go into detail here. You can worship some papers.
Code project's Xiongwen 《Yet another implementation
Of a lock-free circular array queue"
Herb Suter's 《Writing lock-free code:
Corrected queue"-Use the STD: Atomic template of C ++ 11.
IBM developerworks 《Design a concurrent data structure without mutex lock"