key word:std::mutex、std::atomic、benchmark、performance
原文作者:@玄冬Wong
测试案例:8个线程分别执行1250万次累加和累减,累加的最终结果为10亿,累减的最终结果为0。
/************************************************************************/
/*测试std::mutex和std::atomic的性能对比 */
/************************************************************************/
#include <windows.h>
#include <iostream>
#include <time.h>
#include <thread>
#include <list>
#include <atomic>
#include <mutex>
#define LOOP_COUNT 12500000
#define THREAD_COUNT 8
std::atomic<unsigned int>* atomic_array;
std::mutex m;
unsigned int* int_array;
void atomic_fun()
{
for (int i = 0; i < LOOP_COUNT; i++)
{
atomic_array[0]++;
atomic_array[1]--;
}
}
void mutex_fun()
{
for (int i = 0; i < LOOP_