C ++中的非阻塞线程安全队列? [英] non-blocking thread-safe queue in C++?
问题描述
在C ++中有一个线程安全的,非阻塞的队列类吗?
可能是一个基本的问题,但我一直没有做C ++很长时间
假设你的CPU有一个双指针宽的比较和交换(compxchg8b在486或更高,compxchg16b在大多数amd64机器[不存在于一些早期的型号由英特尔])有一个算法此处。
更新:如果你不害怕做一点工作,不难把它翻译成C ++。 :P
此算法假设一个带标签的指针结构,如下所示:
//注意,复制此结构必须以原子方式执行...
template< class T>
struct pointer
{
T * ptr;
uintptr_t tag;
};
然后你想包装指令 lock cmpxchg {8 | 16} b
也许你可以这样写队列节点:
模板< class T>
struct queue_node
{
T value;
指针< queue_node< T> >下一个;
};
其余或多或少是我链接到...的算法的转录
Is there a thread-safe, non-blocking queue class in the C++?
Probably a basic question but I haven't been doing C++ for a long time...
EDIT: removed STL requirement.
Assuming your CPU has a double-pointer-wide compare-and-swap (compxchg8b on 486 or higher, compxchg16b on most amd64 machines [not present on some early models by Intel])... There is an algorithm here.
Update: It's not hard to translate this to C++ if you aren't afraid of doing a bit of work. :P
This algorithm assumes a "pointer with tag" structure which looks like this:
// Be aware that copying this structure has to be done atomically...
template <class T>
struct pointer
{
T *ptr;
uintptr_t tag;
};
Then you want to wrap the instructions lock cmpxchg{8|16}b
with some inline asm...
Maybe then you can write the queue node like this:
template <class T>
struct queue_node
{
T value;
pointer<queue_node<T> > next;
};
The rest is more or less a transcription of the algorithm I linked to...
这篇关于C ++中的非阻塞线程安全队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!