using atom_inc to append to the end of an array

Hi there :slight_smile:

I have an array and some threads that want to insert something to the end of the array. The head of the array is a global int variable. How should I do that?

I was thinking something like this:

atom_inc(&head);
array[head]=new_item;

but I heard the head is now head+number of threads that want to append (first all the atom_incs from all threads finish then the head is read), not +1 to the first thread, than +2 to the second as I would have liked. (put the threads that want to inc in a list, take the first thread, inc, than the thread reads the head than the second comes and increases once more…)

Not all threads add something to the list. How could I do that?

Thank you :slight_smile:

sorry :frowning:
I wasn’t paying attention, I should have posted this in the beginner section :frowning:

anyway, here’s the answer I got:

Following should work for you. oldValue or oldValue + 1 may be your end of the array for that thread based on your initial value of head.

oldValue = atom_inc(&head);

array[oldValue or oldValue + 1] = new_item.