In multithreading, this mode is often used. Thread A pushes elements to queue L, and thread B pushes pop elements from queue L to ensure thread security, the lock must be applied to A push and then the lock must be applied to B pop. This is A typical producer consumer mode, which obviously reduces the efficiency of the program. So how can we optimize this scenario? We can use the flip Queue (also called the exchange Queue) to improve the efficiency of this model. The design idea is to use two queues L1, L2, A or continue to push elements to L1, however, B's pop elements in L2 are switched to L1 and L2 when L2 is empty. In this way, A still needs to be locked for push, but B does not need to be locked for pop, you only need to lock L1 and L2 during the exchange, and the actual conflict is only in the exchange. In this way, the probability of lock mutex is greatly reduced, and the efficiency of the model is optimized. The Code is as follows (the lock code is pseudocode) and is implemented using a template:
template<typename _OBJ>class SwappingList{public:size_t Add(_OBJ & obj ){ResGuard<Mutex> lock(m_frontMutex);m_frontList->push_back(obj);return m_frontList->size();}bool Get(_OBJ & obj ){if ( m_backList->empty() ){Swap();}if ( m_backList->empty() ){return false;}obj = m_backList->front();m_backList->pop_front();return true;}void Swap(){ResGuard<Mutex> lock(m_frontMutex);PRODUCT_LIST * p = m_backList;m_backList = m_frontList;m_frontList = p;}SwappingList(){m_frontList = new PRODUCT_LIST;m_backList = new PRODUCT_LIST;}virtual ~SwappingList(){if ( m_frontList ){delete m_frontList;m_frontList = 0;}if ( m_backList ){delete m_backList;m_backList = 0;}}protected:typedef std::list<_OBJ> PRODUCT_LIST;PRODUCT_LIST* m_frontList;PRODUCT_LIST* m_backList;Mutex m_frontMutex;};