Why is std::atomic much slower than volatile bool?

后端 未结 3 563
走了就别回头了
走了就别回头了 2021-01-31 03:24

I\'ve been using volatile bool for years for thread execution control and it worked fine

// in my class declaration
volatile bool stop_;

-----------------

// I         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 03:49

    Since I'm curious about this, I tested it myself on Ubuntu 12.04, AMD 2.3 GHz, gcc 4.6.3.

    #if 1
    #include 
    std::atomic stop_(false);
    #else
    volatile bool stop_ = false;
    #endif
    
    int main(int argc, char **argv)
    {
        long n = 1000000000;
        while (!stop_) {
            if (--n < 0)
                stop_ = true;
        }
    
        return 0;
    }
    

    Compiled with g++ -g -std=c++0x -O3 a.cpp

    Although, same conclusion as @aleguna:

    • just bool:

      real 0m0.004s
      user 0m0.000s
      sys 0m0.004s

    • volatile bool:

      $ time ./a.out
      real 0m1.413s
      user 0m1.368s
      sys 0m0.008s

    • std::atomic:

      $ time ./a.out
      real 0m32.550s
      user 0m32.466s
      sys 0m0.008s

    • std::atomic:

      $ time ./a.out
      real 0m32.091s
      user 0m31.958s
      sys 0m0.012s

提交回复
热议问题