C++11 线程原子变量和线程安全

// 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;
}

运行结果:

分析:从上述代码结果来看,num并没有变成2000000000,由于线程发生了冲突,从而导致结果不正确。

下面我们加入锁机制

// 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;
}

运行结果:

这次结果正确了,但是耗时太长了,这是因为mutex加解锁需要时间。

再次修改代码,使用原子变量

// 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;
}

运行结果:

结果正确,耗时比用互斥量好一些

扫描二维码关注公众号,回复: 10439924 查看本文章
发布了257 篇原创文章 · 获赞 22 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_24127015/article/details/104799113