• atomic c++ y原子变量 替换锁代码


    #include <iostream>

    #include <thread>

    #include <atomic>

     

    int cnt=0;

     

    class MyLock

    {

    private:

            std::atomic_flag lk = ATOMIC_FLAG_INIT;;

    public:

            MyLock() {};

            void lock();

            void unlock();

    };

     

    void MyLock::lock()

    {

            while (lk.test_and_set())

            {

                    cnt++;

            }

    };

    void MyLock::unlock()

    {

            lk.clear();

    };

     

    MyLock mlk;

    int sum = 0;

    void fun()

    {

            for (int i = 0; i < 100000; ++i)

            {

                    mlk.lock();

                    sum += 1;

                    mlk.unlock();

     

            }

    }

     

    int main()

    {

            std::thread t1(fun);

            std::thread t2(fun);

     

            t1.join();

            t2.join();

     

            std::cout << "sum = " << sum << std::endl;

    }

     

    #编译要用 g++ -pthread -std=c++11 atomic.cc

    有时候,不小心知道了一些事,才发现自己所在乎的事是那么可笑。
  • 相关阅读:
    AbsoluteLayout 相框
    Cursor getContentResolver
    Diary DiaryDbAdapter 日记本程序
    Linkify
    Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
    exampleuse SharedPreferences
    Gallery
    AbsoluteLayout xiantu
    PRD
    android 拨打电话 号码判断
  • 原文地址:https://www.cnblogs.com/axjlxy/p/15266269.html
Copyright © 2020-2023  润新知