C++原子操作和加锁对比

81 阅读1分钟

本文主要是对比为保证原子性,使用C++原子操作和使用加锁的方式的对比。

#define USE_ATOMIC

#include <Windows.h>
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

#ifdef USE_ATOMIC
	#include <atomic>
	std::atomic_long count = 0;
#else
	int count = 0;
#endif



#ifndef USE_ATOMIC
	std::mutex mtx;
#endif // USE_MUTEX


void addCount() {
	for (int i = 0; i < 100000; i++) {
#ifndef USE_ATOMIC
		std::lock_guard<std::mutex> lock(mtx);
#endif
		count += 1;
	}
}

std::vector<std::thread> threads;

int main()
{
	for (int i = 0; i < 10; i++) {
		threads.push_back(std::thread(addCount));
	}

	for (auto& t : threads) {
		t.join();
	}

	std::cout << "count : " << count << std::endl;

}