【问题标题】:Assigning values to an array of atomic user defined structures将值分配给原子用户定义结构的数组
【发布时间】:2017-10-04 18:15:43
【问题描述】:

我正在尝试创建结构变量的原子数组。但我不能为任何数组元素赋值。

   struct snap {
        int number;
        int timestamp;
    };

atomic<snap> *a_table;

void writer(int i, int n, int t1)
{
    int v, pid;
    int t1;
    a_table = new atomic<snap>[n];
    pid = i;
    while (true)
    {
        v = rand() % 1000;
        a_table[pid % n]->number = v;
        this_thread::sleep_for(chrono::milliseconds(100 * t1));
    }
}

a_table[pid % n]-&gt;number = v 行显示错误(表达式必须具有指针类型)

【问题讨论】:

  • a_table[pid % n].number = v;这给出了一个错误 std::atomic has no member number
  • 好的,谢谢,我会修改它并报告有效的方法

标签: c++ pointers struct compiler-errors atomic


【解决方案1】:

a_table[pid % n] 给你一个std::atomic&lt;snap&gt;,而不是那个类型的指针。

但是,你不能直接做你想做的事,你需要使用atomic::store()。所以改变这个:

a_table[pid % n]->number = v;

到这里:

snap tmp {v, myTimestamp};
a_table[pid % n].store(tmp, std::memory_order_relaxed);

PS:进一步阅读:std::atomic 的工作原理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多