An object has a memory pool assigned to it by malloc()
.
This object accesses the memory pool for reading and writing using std::atomic<A> *
.
<A>
could be a class which is trivially copyable type or any standard type.
This object which read and write the memory pool could be called by different threads.
If a thread get a reference to an atomic object for example pointed to a particular memory address of the memory pool and then do some logic with the object, could another thread references to the same atomic object during this time? Does this thread wait until this object is "released" by the other thread or would continue getting another object which is not already referenced? Following code is the algorithm implemented by such use case:
std::atomic<Record> * it_record{&memory_address}; -> memory_address is obtained by malloc()
for(size_t i{0U}; i < m_nbr_record; ++i) {
Record tmp = *it_record;
if (tmp == target_record) {
*it_record = new_record;
found = true;
break;
}
++it_record;
}
Yes. Accessing an object through an atomic variable only guarantees that single atomic operations are executed so that other threads cannot interfere. In your example the reading and writing are each an atomic operation.
No, that is what a mutex does. Again, for atomics a singular operation is atomic, not a sequence of operations.
For your particular use case, it looks like a compare-and-swap (CAS) should work.
Addendum
Being correct and being efficient are two very different things. This kind of operation is somewhat unusual and very inefficient. The description of your algorithm is too vague to give any meaningful advice but a memory pool sounds very much like something best served by a lockfree stack
If you stick with your design, check whether it is possible to change it into a read + CAS loop to avoid the expensive CAS until the correct element is found.
You should also check whether one of the weaker memory orders are possible for CAS but that depends on the specifics of your use-case.