Is using `std::get` on a `std::tuple` guaranteed to be thread-safe for different values of `I`?

Since std::get has no explicit statements in the specification about its data race properties, we fall back to the default behavior defined in [res.on.data.races]. Specifically, paragraphs 2 and 3 tell the story:

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

A C ++ standard library function shall not directly or indirectly modify objects (1.10) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s non-const arguments, including this.

These provide protection from data races only for uses that are not the same object provided by a function’s arguments. A template parameter is not technically a function’s arguments, so it doesn’t qualify.

Your case involves multiple threads passing the same object to different get calls. Since you are passing a non-const parameter, get will be assumed to be modifying its tuple argument. Therefore, calling get on the same object counts as modifying the object from multiple threads. And therefore, calling it can legally provoke a data race on the tuple.

Even though, technically speaking, it’s just extracting a subobject from the tuple and therefore should not disturb the object itself or its other subobjects. The standard does not know this.

However, if the parameter were const, then get would not be considered to provoke a data race with other const calls to get. These would simply be viewing the same object from multiple threads, which is allowed in the standard library. It would provoke a data race with non-const uses of get or with other non-const uses of the tuple object. But not with const uses of it.

So you can “access” them, but not “modify” them.

Leave a Comment

tech