0
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?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Bruice
  • 543
  • 3
  • 11
  • Does `SomeClass` access some global/concurrent variable? – Jarod42 Mar 05 '21 at 10:20
  • Does this answer your question? [Is unique\_ptr thread safe?](https://stackoverflow.com/questions/11482580/is-unique-ptr-thread-safe) – anastaciu Mar 05 '21 at 10:21
  • 1
    Creating _anything_ is "thread safe" in that no single object can be created by more than one thread at a time. But if you are attaching its address to a pointer, only one thread can be accessing that pointer at a time. – Galik Mar 05 '21 at 10:23
  • you need to consider the whole picture. I suppose somewhere you are also accessing the unique pointers that you assigned to elements in the array. Those accesses of course have to be synchronized with creating the elements – 463035818_is_not_an_ai Mar 05 '21 at 10:24
  • Read more: https://stackoverflow.com/questions/11482580/is-unique-ptr-thread-safe/11485874 – Ishara Madushan Mar 05 '21 at 10:43

2 Answers2

1

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326