C++中的+=
運算符是否線程安全?C++中+ =運算符的線程安全性
這是可以想像的情況下它不是(僞):
int a = 5;
void thread1() {
a += 5;
}
void thread2() {
a += 5;
}
void main() {
start_thread1();
start_thread2();
//Prints 15 always, but i think 10 is not impossible.
printf ("%d\n", a);
}
很明顯,我必須使用互斥時+ =超載,但我一定要設置一個互斥時使用簡單的類型?
從寫入有效的C++開始。 –
從多個線程寫入相同(非原子)的數據不是「線程安全」的。 – juanchopanza
@LightnessRacesinOrbit我認爲添加所有pthread樣板代碼不會影響問題的質量。 – Richard