I want an asynchronous thread to edit an object. Therefore I store a pointer to that object.
Data *pointer;
There is also a flag of type std::atomic<bool> to know if the secondary thread is modifying the object the pointer points to or not. While the flag holds true, the main thread won't affect the pointer and its underlying object.
std::atomic<bool> modifying;
void Thread()
{
// wait for jobs
for(;;)
{
// the flag is set to true my the main thread
// to let this thread start processing
if(modifying)
{
// modify the object the pointer points to,
// pass the pointer to a function to do so,
// and so on...
// the flag to false to tell the main thread
// that it can read the result from the pointer
// and prepare it for the next job
modifying = false;
}
}
}
- How can I ensure thread safety?
I cannot wrap the pointer by std::atomic because from the secondary thread I need to pass the pointer to a function expecting a non atomic Data* type as parameter.
- Do pointers even need to be declared as atomic specifically? I don't think that a processor would change threads during writing a single register. Or do I have to make it atomic anyway to prevent unwanted compiler optimizations?
- If a pointer is atomic, is the underlying object so, too? In other words, could I modify the object using the pointer I get from
pointer.load()?
Thanks for your clarification.
Dataor the pointer toData. The question really seems like you are trying to do something other than what atomic is meant for.Threadcode.