高性能併發隊列(C++實現)

算法參考:http://www.parallellabs.com/2010/10/25/practical-concurrent-queue-algorithm/,很是適合生產者-消費者模型。node

注意:一、析構函數沒有加鎖,由於須要同時對head lock和tail lock加鎖。不建議在析構不肯定的狀況下使用。算法

二、經測試,比加鎖的std::list快50%,比加鎖的std::queue慢20%。函數

[cpp] view plaincopyprint?在CODE上查看代碼片派生到個人代碼片測試

template <typename T>  
class concurrent_queue  
{  
public:  
    concurrent_queue()  
    {  
        NODE* node = new NODE();  
        node->next = NULL;  
  
        head_ = node;  
        tail_ = node;  
    }  
  
    ~concurrent_queue()  
    {  
        NODE* node = head_;  
  
        do  
        {  
            node = erase_(node);  
        }  
        while(node != NULL);  
    }  
  
    void push(const T& val)  
    {  
        NODE* node = new NODE();  
        node->val = val;  
        node->next = NULL;  
  
        scoped_lock lock(t_lock_);  
        tail_->next = node;  
        tail_ = node;  
    }  
  
    bool pop(T* val)  
    {  
        scoped_lock lock(h_lock_);  
        if(empty_())  
        {  
            return false;  
        }  
  
        head_ = erase_(head_);  
        *val = head_->val;  
        return true;  
    }  
  
private:  
    struct NODE  
    {  
        T val;  
        NODE* next;  
    };  
  
private:  
    bool empty_() const  
    {  
        return head_->next == NULL;  
    }  
  
    NODE* erase_(NODE* node) const  
    {  
        NODE* tmp = node->next;  
        delete node;  
        return tmp;  
    }  
  
private:  
    NODE* head_;  
    NODE* tail_;  
    concurrent_lock h_lock_;  
    concurrent_lock t_lock_;  
};  


class concurrent_lock  
{  
public:  
    concurrent_lock()  
    {  
        InitializeCriticalSection(&cs_);  
    }  
  
    ~concurrent_lock()  
    {  
        DeleteCriticalSection(&cs_);  
    }  
  
    void lock()  
    {  
        EnterCriticalSection(&cs_);  
    }  
  
    void unlock()  
    {  
        LeaveCriticalSection(&cs_);  
    }  
  
private:  
    CRITICAL_SECTION cs_;  
};  
  
class scoped_lock  
{  
public:  
    scoped_lock(const concurrent_lock& lock) : lock_(lock)  
    {  
        const_cast<concurrent_lock&>(lock_).lock();  
    }  
  
    ~scoped_lock()  
    {  
        const_cast<concurrent_lock&>(lock_).unlock();  
    }  
  
private:  
    const concurrent_lock& lock_;  
};
相關文章
相關標籤/搜索