码给你,自测。
代码语言:javascript复制#include <iostream>
#include <thread>
#include <atomic>
#include <ctime>
#include <mutex>
using namespace std;
std::atomic_int a;
//int a;
std::mutex _mutex;
void add_() {
for (int i = 0; i < 10000; i ) {
_mutex.lock();
a ;
_mutex.unlock();
//printf("%dn", a); //这个有点快啊 3.831
std::cout << a << std::endl;
//cout << a << endl; //有没有std速度差不多
}
}
int main()
{
clock_t startTime, endTime;
//add_(); //一条线程空跑:12.753
//atomic:11.744 下午再测 5.757s
//上锁:11.954 下午再测 5.891s
startTime = clock();//计时开始
std::thread t1(add_);
std::thread t2(add_);
t1.join();
t2.join();
endTime = clock();//计时结束
std::cout << "The run time is: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << std::endl;
system("pause");
return 0;
}