天天看點

printf的線程安全性以及cout的線程不安全性驗證,以及意外收獲

碼給你,自測。

#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("%d\n", 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;
}