Implementation of flipped queue

Source: Internet
Author: User

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;};

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.