Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to modify elements of std::valarray<T> concurrently?

If I've understood correctly, since C++11 it has been safe to call const member functions of a container concurrently and modify the elements of a container as long as the container itself is not modified as part of the operation (as seen from e.g. the table concerning thread safety in cppreference.com). Since std::valarray is not listed in the containers section of the (draft) standard, I'm unsure if thread safety also applies to it. In other words,

  • Is it safe to read from a std::valarray concurrently (in particular by using operator[] with slices)?
  • Is it safe to modify the elements of std::valarray<T> concurrently if the operation on T is safe?

I would like to use std::valarray for a multidimensional array of numbers that would be filled using multiple threads.

like image 794
tsnorri Avatar asked Jul 02 '18 14:07

tsnorri


People also ask

Is Size () thread-safe?

No, they're not thread-safe. The standard containers are simply not thread-safe, period. There is however a limited amount of thread safety: If every thread accesses a different element, and no element is accessed by two distinct threads at any given time, then that's fine.

Is STL thread-safe?

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.


1 Answers

If I am reading your question correctly, [res.on.data.races] protects distinct slices from participating in data races, under

A C++ standard library function shall not directly or indirectly access objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's arguments, including this.

[container.requirements.dataraces] adds extra protection around modifications to distinct elements, which strictly valarray lacks.

like image 153
Caleth Avatar answered Sep 21 '22 07:09

Caleth