Search code examples
c++multithreadinglock-freecondition-variablehappens-before

C++: Can one thread see a newly allocated object as uninitialized if passed through boost lockfree queue?


I'm building a multiple-producer single-consumer mechanism. I want to do something like this, suppose I have access to an instance of boost lockfree queue available for both threads and a synchronizing condition variable:

Thread 1 (producer):

Object * myObj = new Object();
lockfree_queue.push(myObj);
condition_variable.notify();

Thread 2 (consumer):

condition_variable.wait();
Object * myObj = lockfree_queue.pop();
...
delete myObj;

Is there a chance that on a multi-core system Thread 2 shall see myObj as pointing to memory that is uninitialized or to object that is partially initialized (suppose it has some member variables)?


Solution

  • Once new returns and gives you a pointer, the object is fully constructed.

    If there's uninitialized members in the object, then it's the fault of the constructor for not initializing them.

    And it shouldn't be a problem even if the queue contained object instances instead of pointers, as the push call would be fully done before you notify the condition variable, so the other thread will not even pop the queue until the object is pushed.