2017-10-04 89 views
2

我试图创建结构变量的原子数组。但我不能将值分配给任何数组元素。将值分配给原子用户定义结构的数组

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]->number = v是否显示错误(表达式必须有指针类型)

+0

a_table [pid%n] .number = v; 这给出了一个错误std :: atomic 没有会员编号 – Uttaran

+0

好的,谢谢我会修补它并报告工作 – Uttaran

回答

2

a_table[pid % n]给你一个std::atomic<snap>,而不是那种类型的指针。

但是,你不能直接做你想要的,你需要使用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作品。

+1

这就像一个魅力。谢谢 – Uttaran