假设我在Java中实现了Herlihy-Wing Queue:
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;
}
}
}
}
}
我正在使用atomic<int *>
数组的items
数据类型。但是在enqueue方法中,我需要做一些类似items[i].store(&x)
的事情,这显然是错误的,因为它是一个悬空引用。如何正确执行此操作?如果我使用堆,我不知道何时释放该内存。我怎样才能做到这一点?