Thread-safety of writing a std::vector vs plain array

前端 未结 4 2124
离开以前
离开以前 2021-02-07 03:47

I\'ve read on Stackoverflow that none of the STL containers are thread-safe for writing. But what does that mean in practice? Does it mean I should store writab

4条回答
  •  萌比男神i
    2021-02-07 04:37

    For c++11, which specifies rules for data races, the thread-safety of containers is described. A relevant section of the standard is § 23.2.2, paragraph 2:

    Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector, are modified concurrently.

    [ Note: For a vector x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector y, y[0] = true may race with y[1] = true. —end note ]

    The mentioned § 17.6.5.9 essentially bans any concurrent modification by any standard library interface unless specifically allowed, so the section I quote tells you exactly what's allowed (and that includes your usage).

    Since the question was raised by Steve Jessop, paragraph 1 of § 23.2.2 explicitly allows the concurrent use of [] in sequence containers:

    For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].

提交回复
热议问题