您当前的位置: 首页 >  c++
  • 0浏览

    0关注

    1477博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ 原子操作 std::atomic<int>

软件工程小施同学 发布时间:2021-08-23 14:17:54 ,浏览量:0

std::atomic模板类可以使对象操作为原子操作,避免多线程竞争问题;请看如下代码,一目了然

class Test
{
public:    
    Test() = default;

    void CThreadFunc()
    {
        for (int i = 0; i < 10000; ++i)
        {
            //std::lock_guard lck(Test::m_s_ivalue_mutex); //m_iValue需要加锁才可正常工作
            m_iValue++;

            m_atomic_value++;//不加锁,也可正常工作
        }
    }

    void Start()
    {
        std::vector threads;
        for (int i = 0; i < 10; ++i)
        {
            threads.push_back(std::thread(&Test::CThreadFunc, this));
        }

        for (auto& th : threads)
        {
            if (th.joinable())
            {
                th.join();
            }
        }     
        std::cout             
关注
打赏
1665320866
查看更多评论
0.0427s