// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <mutex>
using namespace std;
const int N = 100000000;
int num = 0;
void run()
{
for (int i = 0; i < N; i++) {
num++;
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ", 用时" << end - start << " ms" << endl;
return 0;
}
operation result:
Analysis: From the above results, the code, num did not turn 2 billion, due to the thread clashed, leading to incorrect results.
Let us join lock mechanism
// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <mutex>
using namespace std;
const int N = 100000000;
int num = 0;
std::mutex m;
void run()
{
for (int i = 0; i < N; i++) {
m.lock();
num++;
m.unlock();
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ", 用时" << end - start << " ms" << endl;
return 0;
}
operation result:
The result is correct, but it takes too long, because the mutex locking and unlocking takes time.
Modify the code again, with atomic variables
// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <mutex>
#include <atomic>
using namespace std;
const int N = 100000000;
//int num = 0;
atomic_int num = 0;
void run()
{
for (int i = 0; i < N; i++) {
num++;
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ", 用时" << end - start << " ms" << endl;
return 0;
}
operation result:
The result is correct, consuming better than with some of the mutex