Can I make a thread-safe std::atomic>?

前端 未结 3 1481
醉话见心
醉话见心 2020-12-11 00:40

I\'m having a function that needs to be executed n=1000 times. This functions does a Monte Carlo style simulation and returns an int as the result.

3条回答
  •  隐瞒了意图╮
    2020-12-11 00:51

    C++11 §29.5/1 says

    There is a generic class template atomic. The type of the template argument T shall be trivially copyable (3.9).

    What does trivially copyable mean?

    §3.9 tells

    Scalar types, trivially copyable class types (Clause 9), arrays of such types, and cv-qualified versions of these types (3.9.3) are collectively called trivially copyable types.

    For class types (of which std::vector is):

    A trivially copyable class is a class that:

    • has no non-trivial copy constructors
    • has no non-trivial move constructors
    • has no non-trivial copy assignment operators
    • has no non-trivial move assignment operators
    • has a trivial destructor

    According to this list std::vector is not trivially copyable and so you cannot use std::atomic>.

    Since you know the size in advance and since you do not need to use methods that would require the vector be reallocated in a different location (like push_back). You can use std::vector::resize or the size constructor to preallocate and preconstruct the required ints. Therefore your concurrent threads do not need to operate on the vector itself but on the elements.

    If there is no access from different threads to the same element there is no race condition.

    The same goes for int k[1000] which is trivially copyable. But you do not need it to be since the threads do not change the array/vector/list itself but the elements.

提交回复
热议问题