std::atomic 原子操作

类模板

template  struct atomic;

 多线程小结:

  • 非原子操作,不加锁,效率很高,但无法得到正确的结果
  • 非原子操作,加锁,效率很低,但结果正确
  • 原子操作,效率很高,且结果正确

 

std::atomic 原子操作_第1张图片 

  • 原子操作是指不会被线程调度机制打断的操作。这种操作一旦开始,就一直运行到结束,中间不会有任何任何上下文切换。
  • 原子操作可以是一个步骤,也可以是多个操作步骤,但其顺序不可被打乱,也不可以被切合只执行其中一部分。
  • 将整个操作视作一个整体是原子操作的核心特征。

 n++;//这条指令不是原子操作

std::atomic 原子操作_第2张图片std::atomic 原子操作_第3张图片

 std::atomic 原子操作_第4张图片std::atomic 原子操作_第5张图片

 

 编程实验

  • 非原子操作,不加锁,效率很高,但无法得到正确的结果
  • 非原子操作,加锁,效率很低,但结果正确
  • 原子操作,效率很高,且结果正确

测试1:非原子操作,无锁

#include 
#include 
using namespace::std;
int g_sum = 0;
void add()
{
    for (uint32_t i=0; i<10000000; ++i)
        ++g_sum;
}

int main()
{
   auto beginTime = clock();
   thread t1(add);
   thread t2(add);
   t1.join();
   t2.join();
   auto endTime = clock();
   cout << "time consuming  : " << endTime - beginTime << endl;
   cout << "calculated value: " <<  g_sum << endl;

    return 0;
}

输出:[速度快,结果错误]

time consuming  : 47
calculated value: 10856025

测试2:非原子操作,有锁

#include 
#include 
#include 

using namespace::std;
int g_sum = 0;
mutex g_mutex;

void add()
{
    for (uint32_t i=0; i<10000000; ++i)
    {
        g_mutex.lock();
        ++g_sum;
        g_mutex.unlock();
    }
}

int main()
{
   auto beginTime = clock();
   thread t1(add);
   thread t2(add);
   t1.join();
   t2.join();

   auto endTime = clock();
   cout << "time consuming  : " << endTime - beginTime << endl;
   cout << "calculated value: " <<  g_sum << endl;

    return 0;
}

输出:[结果正确,速度慢]

time consuming  : 571
calculated value: 20000000

测试3:原子操作 atomic g_sum {0};

#include 
#include 
#include 

using namespace::std;

atomic g_sum {0};

void add()
{
    for (uint32_t i=0; i<10000000; ++i)
    {
        ++g_sum;
    }
}

int main()
{
   auto beginTime = clock();

   thread t1(add);
   thread t2(add);

   t1.join();
   t2.join();
   auto endTime = clock();
   cout << "time consuming  : " << endTime - beginTime << endl;
   cout << "calculated value: " <<  g_sum << endl;

    return 0;
}

输出:[速度快,结果正确]

time consuming  : 292
calculated value: 20000000

一般用法

  • 用于多线程环境中的访问标记
  • 用于多线程环境中的访问统计
#include 
#include 
#include 
using namespace::std;
atomic g_ifEnd {false};

void mythread()
{
    cout << "mythread begin" << endl;
    chrono::microseconds dura(1000);
    while (!g_ifEnd)
    {
        cout << "mythread thread id :" << this_thread::get_id() << endl;
        this_thread::sleep_for(dura);
    }
    cout << "mythread begin" << endl;
}

int main()
{
   cout << "main end" << endl;
   thread t1(mythread);
   this_thread::sleep_for(chrono::microseconds(5000));
   g_ifEnd = true;
   t1.join();
   cout << "main end" << endl;
    return 0;
}

输出:

main end
mythread begin
mythread thread id :2
mythread begin
main end

【C++并发与多线程】 10_shared_future、automic - C_经典C_数据结构_现代C_现代C_多线程_C_内存管理_Linux网络编程 - SegmentFault 思否

你可能感兴趣的:(c++11并发与多线程,c++,算法,开发语言)