1

Let's say I have an implementation of the Herlihy-Wing Queue in Java :

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;
                }
            }
        }
    }
}

I am using the type atomic<int *> data type for the items array. But in the enqueue method, I need to do something like items[i].store(&x) which is wrong obviously since it's a dangling reference. How to do this operation correctly? If I use heap, I don't know when to free that memory either. How can I achieve this?

Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • Its typical to use pointers in the array, but don't use smart pointers here, they don't play well with multithreading. – Passer By Sep 24 '17 at 05:51
  • So, should I use `atomic * items[CAPACITY]` in this ? @PasserBy – Jarvis Sep 24 '17 at 05:52
  • No no, `atomic items[CAPACITY];` Also be sure to read up on the semantics of atomics in C++. Ignore `memory_order_xxx` and friends. – Passer By Sep 24 '17 at 05:53
  • Got it. But when I load a value from type `atomic`, it will return `T*`. Is it guaranteed that dereferencing this `T*` will return a correct value in a multithreaded environment? @PasserBy – Jarvis Sep 24 '17 at 05:55
  • If you directly translate the above code to C++, looks fine to me. – Passer By Sep 24 '17 at 05:59

0 Answers0