Category : atomic

When using atomic type in c++ Why does std::atomic<T>::operator= should return a value instead of reference? It’s not like other common assignment operator which returns a reference. From a cppreference site I can get some hint. Unlike most assignment operators, the assignment operators for atomic types do not return a reference to their left-hand arguments. ..

Read more

Given the following simple lock-free linear allocation algorithm I made: bool allocate(size_type size, size_type& offset) { size_type pos; size_type new_pos; do { pos = m_pos.load(std::memory_order_acquire); new_pos = pos + size; if (new_pos > m_end) return false; } while (!m_pos.compare_exchange_weak(pos, new_pos, std::memory_order_acq_rel, std::memory_order_acquire)); offset = pos; return true; } I would like to improve it further ..

Read more

I’ve read https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange Atomically compares the object representation (until C++20)value representation (since C++20) of *this with that of expected, and if those are bitwise-equal, replaces the former with desired (performs read-modify-write operation). Otherwise, loads the actual value stored in *this into expected (performs load operation). So as I understand the code like bool expected=true; extern ..

Read more

I am solving leetcode task https://leetcode.com/problems/print-foobar-alternately/ I have two solutions The first — OK (passed tests) I used condition_variable to synchronize threads. // First class FooBar { private: int n; condition_variable cv_; int iteration_; mutex m_; public: FooBar(int n) { this->n = n; iteration_ = 0; } void foo(function<void()> printFoo) { unique_lock<mutex> lock(m_); for (int ..

Read more

I have two questions: In the general case is it safe to use an atomic as a T and switch between them interchangeably? In the case of a futex is it safe to do the cast? I am aware that performing atomic operations on non-atomic types is undefined behaviour but I cannot find an answer ..

Read more