Read thread calls at(i)
function and write thread calls push_back()
function, I get the error "out of range", Why?
Asked
Active
Viewed 307 times
0

egraldlo
- 183
- 2
- 11
-
I think that the variable of `size()` remains in each core's register? by using `volatile`, can we solve the problem for the certain situation that "one read one write"? – egraldlo Nov 15 '16 at 11:05
-
No, that's still UB. – Baum mit Augen Nov 15 '16 at 11:08
-
write a self defined queue, define function `size()` by using `volatile` variable count. – egraldlo Nov 15 '16 at 11:12
-
1You cannot use `volatile` for synchronization. Period. Writing a concurrent queue is not *that* easy. – Baum mit Augen Nov 15 '16 at 11:14
1 Answers
3
Calling any non-const member function on any standard library object is not thread-safe (unless a particular non-const function is documented otherwise). You need to synchronise access to the object to prevent data races and thus Undefined Behaviour.

Angew is no longer proud of SO
- 167,307
- 17
- 350
- 455