What is the effective way to initialize shared memory

My program need to use shared memory with some initialization data.

In the begining I use:
shared unsigned int data2[4] = {1, 2, 3, 4};

But nvcc report error “initializer not allowed for shared variable”.

Is there any convenient way to initialize shared memory?

Let a single thread do it

if (threadIdx.x == 0) {

  data2[0] = 1;

  data2[1] = 2;

  // etc



or let multiple threads based on their index do it if it is many elements.

data2[threadIdx.x] = threadIdx.x;


nice answer. Thanks.

That is nice.

All depends on if the value you are putting into each array element can be derived from the threadIdx
if it can’t and there are only a few values then Bloodhunt’s code using thread 0 is way to go

but if it can then using multiple threads working in parrallel, as nachovall did, will do it faster.