Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

c++ - how do I initialise an atomic_flag variable if it is a member of a class?

I'm trying to implement a spin lock using an atomic_flag. I know that with C++11 I have to initialise the atomic_flag variable, but I can't get it to compile. My code looks like this:

class SpinLock 
{
 public:
  SpinLock()
   :m_flag(ATOMIC_FLAG_INIT)  /// syntax error : missing ')' before '{'
  {
  }

  void lock()
  {
    while (m_flag.test_and_set() == true){}
  }

  void unlock()
  {
    m_flag.clear();
  }

 private:
  SpinLock &operator=(const SpinLock &);

 private:
  std::atomic_flag    m_flag;
};

When I compile the code I get 'syntax error : missing ')' before '{''. I also see that ATOMIC_FLAG_INIT is defined as {0}, but what is the correct way to write this then?

The following compiles, but is it still threads safe?

  SpinLock()
  {
         m_flag.clear();
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Visual Studio 2012 does not support c++11 initializer lists (see the c++11 support page)

It is however supported in Visual Studio 2013, (see the "initializer_list Constructors" section in the Uniform Initialization docs)

Meanwhile in your case the constructor can just use an assignment m_flag = ATOMIC_FLAG_INIT;

Update: It seems it did not test the above assignment, but using m_flag.clear(); achieves the same result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...