原子类型非线程安全
#include <iostream>
#include <thread>
int main() {
int num = 0;
int count = 100000;
std::thread thread1([&](){
for(int i = 0; i < count; i++){
num++;
}
});
std::thread thread2([&](){
for(int i = 0; i < count; i++){
num++;
}
});
std::thread thread3([&](){
for(int i = 0; i < count; i++){
num++;
}
});
std::thread thread4([&](){
for(int i = 0; i < count; i++){
num++;
}
});
thread1.join();
thread2.join();
thread3.join();
thread4.join();
std::cout << "num: " << num << std::endl;
return 0;
}
预期结果
400000
实际结果
线程安全代码
atomic
#include <iostream>
#include <thread>
#include <atomic>
int main() {
std::atomic<int> num(0);
int count = 100000;
std::thread thread1([&](){
for(int i = 0; i < count; i++){
num++;
}
});
std::thread thread2([&](){
for(int i = 0; i < count; i++){
num++;
}
});
std::thread thread3([&](){
for(int i = 0; i < count; i++){
num++;
}
});
std::thread thread4([&](){
for(int i = 0; i < count; i++){
num++;
}
});
thread1.join();
thread2.join();
thread3.join();
thread4.join();
std::cout << "num: " << num << std::endl;
return 0;
}
std::mutex
#include <iostream>
#include <thread>
#include <mutex>
class Num{
public:
Num(){
num = 0;
}
void add(){
std::lock_guard<std::mutex> lock(mtx);
num++;
}
int getNum(){
std::lock_guard<std::mutex> lock(mtx);
return num;
}
private:
int num;
std::mutex mtx;
};
int main() {
Num num;
int count = 100000;
std::thread thread1([&](){
for(int i = 0; i < count; i++){
num.add();
}
});
std::thread thread2([&](){
for(int i = 0; i < count; i++){
num.add();
}
});
std::thread thread3([&](){
for(int i = 0; i < count; i++){
num.add();
}
});
std::thread thread4([&](){
for(int i = 0; i < count; i++){
num.add();
}
});
thread1.join();
thread2.join();
thread3.join();
thread4.join();
std::cout << "num: " << num.getNum() << std::endl;
return 0;
}