2

I'm trying to create an atomic array of a structure variable. But I cannot assign values to any array element.

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

The line a_table[pid % n]->number = v is showing an error (expression must have pointer type)

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Uttaran
  • 59
  • 6

1 Answers1

2

a_table[pid % n] gives you a std::atomic<snap>, not a pointer of that type.

However, you cannot do what you want direcly, you need to use atomic::store(). So change this:

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

to this:

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

PS: Further read: How std::atomic works.

user4581301
  • 33,082
  • 7
  • 33
  • 54
gsamaras
  • 71,951
  • 46
  • 188
  • 305