1

I am using spin lock to implement a concurrent queue.

AFAIK, while thread 1 changes thread-shared memory, thread 2 may not see this modification. It is called memory visibility.

While I am using mutex, it can make sure the memory visibility for other threads. But in spin lock case, will it act the same as mutex case?

Here is the test code:

class Spin
{
public:
    void lock() {
        while (locked.test_and_set(std::memory_order_acquire));
    }
    void unlock() {
        locked.clear(std::memory_order_release);
    }
protected:
    std::atomic_flag locked = ATOMIC_FLAG_INIT ;
};

template <typename T>
class ConcurrentQueue
{
public:
    void push(const T& value) {
        m_spin.lock();
        m_queue.push(value);
        m_spin.unlock();
    }
    T pop() {
        m_spin.lock();
        T value = m_queue.front();
        m_queue.pop();
        m_spin.unlock();
        return value;
    }
protected:
    std::queue<T> m_queue;//Should I change it to std::queue<std::atomic<T>> or other memory synchronous
    Spin m_spin;
};
Community
  • 1
  • 1
Ringo_D
  • 784
  • 5
  • 18
  • I would be more concerned about the fact that if any queue operation throws an exception, you will never reach the `unlock()`. – Bo Persson Mar 02 '17 at 09:37
  • Creating a concurrent queue is a super-classical problem. Why don't you look into the implementations provided in this book, for example? https://www.amazon.com/C-Concurrency-Action-Practical-Multithreading/dp/1933988770 – The Quantum Physicist Mar 02 '17 at 09:42
  • @TheQuantumPhysicist Thanks for your suggestion. I will read this book. – Ringo_D Mar 02 '17 at 11:38

0 Answers0