Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Does an array of atomics also need to be atomic?

I have some code like the following:

KMessageQueue::KMessageQueue()
{    
    messages = new atomic<KBuffer*>[MAX_MESSAGES];
    for (int i = 0; i < MAX_MESSAGES; i++)
        messages[i].store(nullptr);
}

Where messages is a member of KMessageQueue, defined as:

std::atomic<KBuffer*>* messages;

So each element in the messages array is atomic, and I read them from another thread. But does the array pointer itself also need to be atomic? Could another thread try to access a message after the constructor completes, only to discover that messages hasn't been assigned a value yet?

like image 395
Ebonair Avatar asked Oct 18 '22 21:10

Ebonair


1 Answers

But does the array pointer itself also need to be atomic?

In general it depends on how that pointer is used by different threads. If one thread may modify it when other(s) read then yes. In your case no, you do not need it. Assuming your program is correct (otherwise answer does not make any sense) you cannot use instance of your class until it is fully constructed ie constructor finishes.

Could another thread try to access a message after the constructor completes, only to discover that messages hasn't been assigned a value yet?

It is your job to make that class inaccessible by multiple threads until it is fully initialized. After that it should be fine.

like image 55
Slava Avatar answered Oct 21 '22 03:10

Slava