Posts

Showing posts with the label atomic

Can two stores be reordered in such singleton implementation?

Can two stores be reordered in such singleton implementation? In the following singleton 'get' function, can other threads see instance as not-null, but almost_done still false? (Say almost_done is initially false .) instance almost_done almost_done false Singleton *Singleton::Get() { auto tmp = instance.load(std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire); if (tmp == nullptr) { std::lock_guard<std::mutex> guard(lock); tmp = instance.load(std::memory_order_relaxed); if (tmp == nullptr) { tmp = new Singleton(); almost_done.store(true, std::memory_order_relaxed); // 1 std::atomic_thread_fence(std::memory_order_release); instance.store(tmp, std::memory_order_relaxed); // 2 } } return tmp; } If they can, why? What's the rationale? I know nothing can "get out" of an acquire-release section, but can't 2 enter it and be reorder...

Atomicness for a global variable shared by threads

Atomicness for a global variable shared by threads Okay, trivial question. Problem is, every answer I find on here has 3/4 conflicting answers. I have a very simple problem. I have a global variable called ABORT_SIGNAL. As of now, this is declared volatile int ABORT_SIGNAL . I understand that this does not do what I wish... which is... volatile int ABORT_SIGNAL I have two threads which may write to ABORT_SIGNAL. It will start at 0, and go to 1 after a number of seconds. Every other thread will be reading this variable on a regular basis, checking to see if the value has been set to 1. Would the following achieve this .... #include <stdint.h> atomic_int ABORT_SIGNAL; ... // When updating the value ... atomic_store(&ABORT_SIGNAL, someValue); // When reading the value ... if (atomic_load_explicit(&ABORT_SIGNAL, memory_order_relaxed)) doSomething() Others have also suggested that I would need to do something like the following. After each write issue atomic_thread_fence(m...