可能通过mutex或用lock_guard加锁,保证 counter++的原子性操作。
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <chrono>
#include <stdexcept>
using namespace std;
int counter = 0;
std::mutex mtx;
void increase(int time) {
for (int i = 0; i < time; i++) {
//mtx.lock();
//std::lock_guard<std::mutex> lk(mtx);
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
//mtx.unlock();
}
}
int main(int argc, char** argv) {
std::thread th1(increase, 100);
std::thread th2(increase, 100);
cout << "mytest:" << endl;
th1.join();
th2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}