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

前端 未结 2 379
無奈伤痛
無奈伤痛 2020-12-30 20:16

Let\'s say I have

std::tuple my_tuple{x0, x1, x2};

where T0, T1 and T2 are value

相关标签:
2条回答
  • 2020-12-30 20:50

    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.

    0 讨论(0)
  • 2020-12-30 21:06

    The short answer is that it depends on the types and what does process do instead of get. By itself, get merely retrieve the address of the object and return it as a reference. Retrieving the address is mostly just reading the contents of integers. It does not raise race conditions. Roughly speaking, the code snippet in your question is thread-safe if and only if the following is thread-safe,

    T1 t1;
    T2 t2;
    T3 t3;
    
    std::thread{[&]{process(t1);}}.detach();
    std::thread{[&]{process(t2);}}.detach();
    std::thread{[&]{process(t3);}}.detach();
    
    0 讨论(0)
提交回复
热议问题