如果atomic_flag变量是类的成员,我如何初始化它? [英] how do I initialise an atomic_flag variable if it is a member of a class?

查看:823
本文介绍了如果atomic_flag变量是类的成员,我如何初始化它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用atomic_flag实现自旋锁。我知道用C ++ 11我必须初始化atomic_flag变量,但我不能得到它编译。我的代码如下:

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;
};

当我编译代码时,我得到'语法错误:missing')'before'{''。我还看到ATOMIC_FLAG_INIT定义为{0},但是这是正确的写法呢?

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?

下面的编译,但它仍然是线程安全的? / p>

The following compiles, but is it still threads safe?

  SpinLock()
  {
         m_flag.clear();
  }


推荐答案

Visual Studio 2012不支持c ++ 11初始值列表(请参阅c ++ 11支持页面

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

但是在Visual Studio 2013中支持它(参见均匀初始化文档

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

同时在你的情况下,构造函数可以使用一个赋值 m_flag = ATOMIC_FLAG_INIT;

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

更新:
似乎没有测试上述作业,使用 m_flag.clear(); 获得相同的结果

这篇关于如果atomic_flag变量是类的成员,我如何初始化它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆