Bruice
Bruice

Reputation: 663

Is creating unique_ptr thread safe

std::array<unique_ptr<SomeClass>, 1000> globalArray;

void foo(int index)
{
   globalArray[index] = make_unique<SomeClass>();
//or globalArray[index] = std::unique_ptr<SomeClass> p(new SomeClass); ?
}

considering here that I'm sure about index that are passed to the foo, that they will not repeat and will not exceed globalArray's capacity, so don't need to check it, will this code be thread-safe?

Upvotes: 0

Views: 966

Answers (2)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29965

If 2 or more threads access the same memory where at least 1 of the accesses is a write, you have race condition. In your example, if you are sure that the indices are different and no 2 threads try to write to the same memory, it's safe. Modifying different elements of the same array from different threads is safe, even though it may cause false-sharing.


I highly recommend this talk by Scott Meyers which goes more in detail about exactly what you're doing and how false-sharing relates to that.

Upvotes: 1

eerorika
eerorika

Reputation: 238311

Is creating unique_ptr thread safe

The creation of std::unique_ptr from the pointer is thread safe. Furthermore, accessing a unique index of an array is thread safe.

Although constructors are often thread safe, we cannot know whether the default constructor of SomeClass is safe without knowing its definition.

Furthermore, accessing the created pointer from other threads later will require synchronisation.

Note that writing adjacent indices of an array of pointers from separate threads is a case where false sharing may impede the performance.

Upvotes: 1

Related Questions