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