高性能同時キュー(C++実現)
1840 ワード
アルゴリズムの参照:http://www.parallellabs.com/2010/10/25/practical-concurrent-queue-algorithm/生産者向けの消費者モデルです。
注意:1、コンストラクタはロックをかけていません。head lockとtail lockにロックを同時にかける必要があります。解析的に不確定な場合の使用は推奨されない。
2、テストした結果、ロックをかけるstd:listより50%速く、ロックをかけるstd:queueより20%遅いです。
注意:1、コンストラクタはロックをかけていません。head lockとtail lockにロックを同時にかける必要があります。解析的に不確定な場合の使用は推奨されない。
2、テストした結果、ロックをかけるstd:listより50%速く、ロックをかけるstd:queueより20%遅いです。
template
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(lock_).lock();
}
~scoped_lock()
{
const_cast(lock_).unlock();
}
private:
const concurrent_lock& lock_;
};