Java 在这种情况下使用适当的原子指针
假设我在Java中实现了Herlihy Wing队列:Java 在这种情况下使用适当的原子指针,java,c++,atomic,atomicinteger,atomicreference,Java,C++,Atomic,Atomicinteger,Atomicreference,假设我在Java中实现了Herlihy Wing队列: public class HWQueue<T> { AtomicReference<T>[] items; AtomicInteger tail; static final int CAPACITY = 1024; public HWQueue() { items =(AtomicReference<T>[])Array.newInstance(Atomi
public class HWQueue<T> {
AtomicReference<T>[] items;
AtomicInteger tail;
static final int CAPACITY = 1024;
public HWQueue() {
items =(AtomicReference<T>[])Array.newInstance(AtomicReference.class, CAPACITY);
for (int i = 0; i < items.length; i++) {
items[i] = new AtomicReference<T>(null);
// Each value in 'items' set to 'null'
// to indicate empty position for enqueue
}
tail = new AtomicInteger(0);
}
public void enq(T x) {
int i = tail.getAndIncrement();
items[i].set(x);
}
public T deq() {
while (true) {
int range = tail.get();
for (int i = 0; i < range; i++) {
T value = items[i].getAndSet(null);
if (value != null) {
return value;
}
}
}
}
}
公共类队列{
原子参考[]项;
原子尾;
静态最终整数容量=1024;
公共队列(){
items=(AtomicReference[])Array.newInstance(AtomicReference.class,CAPACITY);
对于(int i=0;i
我正在为
项
数组使用类型原子
数据类型。但是在enqueue方法中,我需要执行类似于items[I].store(&x)
的操作,这显然是错误的,因为它是一个悬空引用。如何正确执行此操作?如果我使用heap,我也不知道什么时候释放内存。如何实现这一点?通常在数组中使用指针,但这里不要使用智能指针,因为它们不能很好地处理多线程。因此,我应该在这里使用atomic*items[CAPACITY]
@路人编号,原子物品[容量]代码>也一定要阅读C++中原子的语义。忽略memory\u order\u xxx
和朋友。明白了。但是当我从类型atomic
加载一个值时,它将返回T*
。是否可以保证在多线程环境中取消引用此T*
将返回正确的值@PasyBy如果你直接把上面的代码翻译成C++,我就觉得很好。它在数组中使用指针是典型的,但是这里不使用智能指针,它们在多线程中不好用。所以,我应该在代码中使用<代码>原子*项[容量] <代码>吗?路人编号,原子物品[容量]代码>也一定要阅读C++中原子的语义。忽略memory\u order\u xxx
和朋友。明白了。但是当我从类型atomic
加载一个值时,它将返回T*
。是否可以保证在多线程环境中取消引用此T*
将返回正确的值@如果你直接把上面的代码翻译成C++,我就觉得不错。