# Shared memory mechanism

**URL:** <https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265>\
**Category:** CUDA Programming and Performance\
**Created:** [January 7, 2008, 7:29pm UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265 "2008-01-07T19:29:34Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![aviad](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@aviad](https://forums.developer.nvidia.com/u/aviad)\
**Post date:** [January 7, 2008, 7:29pm UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/1 "2008-01-07T19:29:34Z")

</div>

Hello,

The following function darkens an image.

With shared memory:

```auto
__global__ void

darkenImage( float* g_odata, int width, int height, int iterNum) 

{

	// calculate texture coordinates

	float factor = 0.9999;

	unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;

	unsigned int y = blockIdx.y*blockDim.y + threadIdx.y;

	__shared__ float g_odatas;

	g_odatas = factor*tex2D(tex, x, y);

	for (int i=1; i<iterNum; i++){

	// read from texture and write to global memory

	g_odatas = factor*g_odatas;

	

	}

	g_odata[y*width + x] = g_odatas;

}

```

Without shared memory:

```auto
__global__ void

darkenImage( float* g_odata, int width, int height, int iterNum) 

{

	// calculate texture coordinates

	float factor = 0.9999;

	unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;

	unsigned int y = blockIdx.y*blockDim.y + threadIdx.y;

	g_odata[y*width + x] = factor*tex2D(tex, x, y);

	for (int i=1; i<iterNum; i++){

	// read from texture and write to global memory

	g_odata[y*width + x]= factor*g_odata[y*width + x];

	

	}

}

```

My question is: Why does this code work?

Fact: Using shared memory accelerates this function dramaticaly.

I am unable to understand the shared memory mechanism.

Does every thread in the block redefines g\_odatas? if so then how is it shared?

If not then why my pictures still get darkened alright?

Anyway, where can I find a good reference to an (beginner/intermediate) article explaining how to work with shared memory in cuda? (I am especialy intrested in image manipulation)

Thanks in advance,

Aviad.

---

<div class="post-metadata">

**Author:** ![DenisR](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@DenisR](https://forums.developer.nvidia.com/u/DenisR)\
**Post date:** [January 8, 2008, 8:59am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/2 "2008-01-08T08:59:39Z")

</div>

The one with shared memory can not work like that, Are you sure that your image does not get distorted in blocks?. You could make it work if you change your code to :

```auto
__global__ void

darkenImage( float* g_odata, int width, int height, int iterNum)

{

// calculate texture coordinates

float factor = 0.9999;

unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;

unsigned int y = blockIdx.y*blockDim.y + threadIdx.y;

__shared__ float g_odatas[NUM_THREADS];

unsigned int index =  threadIdx.x * blockDim.x + threadIdx.y

g_odatas[index] = factor*tex2D(tex, x, y);

for (int i=1; i<iterNum; i++)

  g_odatas[index] = factor*g_odatas[index];

g_odata[y*width + x] = g_odatas[index];

}

```

But I would never use shared memory here, since you do not need to communicate between threads. So just use a register (take away the **shared** ). Also your code can be probably be much faster when you do this :

```auto
__global__ void

darkenImage( float* g_odata, int width, int height, int iterNum)

{

// calculate texture coordinates

float factor = 0.9999;

unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;

unsigned int y = blockIdx.y*blockDim.y + threadIdx.y;

g_odata[y*width + x] = powf(factor, (float) iterNum) * tex2D(tex, x, y);

}

```

---

<div class="post-metadata">

**Author:** ![aviad](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@aviad](https://forums.developer.nvidia.com/u/aviad)\
**Post date:** [January 8, 2008, 9:43am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/3 "2008-01-08T09:43:05Z")

</div>

Hey,  
Thanks for the quick and useful reply!

You are right about the usage of powf, however, this function isn’t the key of my work, I just use it to test some ideas before I implement them in the real kernel.

However, if I got you right, then when I declare a shared memory array, it is only defined once? means that the first thread that is executed is responsible for it?  
In addition, when you wrote:

**shared** float g\_odatas[NUM\_THREADS];

It means that NUM\_THREADS is the total number of threads in the grid? isn’t it supposed to be the total number of threads per block?

Thanks!

---

<div class="post-metadata">

**Author:** ![AndreiB](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/andreib/32/9727_2.png) [@AndreiB](https://forums.developer.nvidia.com/u/AndreiB)\
**Post date:** [January 8, 2008, 9:50am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/4 "2008-01-08T09:50:47Z")

</div>

> [@](#):
>
> However, if I got you right, then when I declare a shared memory array, it is only defined once? means that the first thread that is executed is responsible for it?

You can also declare your **shared** array outside kernel, it may be easier to understand it in this way.

> [@](#):
>
> It means that NUM\_THREADS is the total number of threads in the grid?

This is number of threads per block.

---

<div class="post-metadata">

**Author:** ![aviad](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@aviad](https://forums.developer.nvidia.com/u/aviad)\
**Post date:** [January 8, 2008, 10:08am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/5 "2008-01-08T10:08:55Z")

</div>

> [@](#):
>
> You can also declare your **shared** array outside kernel, it may be easier to understand it in this way.
> 
> This is number of threads per block.
> 
> [snapback]306830[/snapback]

But if I declare it outside the kernel, is it still shared for each block? What is the difference between declaring the array outside the kernel and declaring it inside the kernel?

Thanks

---

<div class="post-metadata">

**Author:** ![DenisR](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@DenisR](https://forums.developer.nvidia.com/u/DenisR)\
**Post date:** [January 8, 2008, 10:46am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/6 "2008-01-08T10:46:33Z")

</div>

> [@](#):
>
> But if I declare it outside the kernel, is it still shared for each block? What is the difference between declaring the array outside the kernel and declaring it inside the kernel?
> 
> Thanks
> 
> [snapback]306837[/snapback]

There is no difference. The shared memory is shared between all the threads in a block (so in the above code it would be threadDim.x \* threadDim.y). The only difference is :

- when you declare it in your kernel, you need to know the size at compile-time.

- when you declare it outside your kernel you can allocate it at runtime, but you can only have 1 array then (so you need to make pointers into the array when you need more than 1 shared array in your kernel. There is an example in the documentation I believe.

---

<div class="post-metadata">

**Author:** ![HenryAbra](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@HenryAbra](https://forums.developer.nvidia.com/u/HenryAbra)\
**Post date:** [January 8, 2008, 11:27am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/7 "2008-01-08T11:27:02Z")

</div>

Hello,

I am new to CUDA too and I am a 3rd year SE student.

Correct me if I’m wrong:

Each shared memory declared in the kernel of size Z will be allocated once (_When is it allocated?) and the total size of the allocated memory will be of size Z_blockDim.x \* blockDim.y.  
If so then each block of threads will share that memory of size Z.

Did I understand it right?

---

<div class="post-metadata">

**Author:** ![DenisR](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@DenisR](https://forums.developer.nvidia.com/u/DenisR)\
**Post date:** [January 8, 2008, 11:33am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/8 "2008-01-08T11:33:59Z")

</div>

No, you did not understand it good.

If you declared **shared** float dummy[2] in your kernel, then each block will have 2 floating point elements shared. If you declared **shared** float dummy[threadDim.x \* threadDim.y], then you would have 1 floating point element for each thread in the block. It would not work btw, since you need to know the size at compile time when declaring it in your kernel. It is ‘allocated’ before your block runs.

Read up on shared memory in the docs, it is quite extensive on the subject. Also the SDK has many examples using shared memory in different ways.

---

<div class="post-metadata">

**Author:** ![HenryAbra](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@HenryAbra](https://forums.developer.nvidia.com/u/HenryAbra)\
**Post date:** [January 8, 2008, 11:57am UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/9 "2008-01-08T11:57:31Z")

</div>

> [@](#):
>
> No, you did not understand it good.
> 
> If you declared **shared** float dummy[2] in your kernel, then each block will have 2 floating point elements shared. If you declared **shared** float dummy[threadDim.x \* threadDim.y], then you would have 1 floating point element for each thread in the block. It would not work btw, since you need to know the size at compile time when declaring it in your kernel. It is ‘allocated’ before your block runs.
> 
> Read up on shared memory in the docs, it is quite extensive on the subject. Also the SDK has many examples using shared memory in different ways.
> 
> [snapback]306855[/snapback]

I think thats what I said, maybe I am wrong.

For example:

The total number of blocks is: gridDim.x \* gridDim.y (lets say 16x12)

Each block share Z memory elements: lets say I declared: **shared** float dummy[2] → Z=2

That sums up to a total memory elements of: Z_gridDim.x \* gridDim.y → 2_16\*12

Am I still wrong?

(edit) blockDim=\> gridDim my mistake

---

<div class="post-metadata">

**Author:** ![AndreiB](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/andreib/32/9727_2.png) [@AndreiB](https://forums.developer.nvidia.com/u/AndreiB)\
**Post date:** [January 8, 2008, 1:39pm UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/10 "2008-01-08T13:39:58Z")

</div>

When thinking about shared memory forget about your grid, you should consider only block size.

So, if you have 12x16 block of threads and you declare **shared** float dummy[2] in kernel body then only 2-element array will be allocated which will be shared among all 12x16 threads in block.

This is exactly what DenisR have already said.

---

<div class="post-metadata">

**Author:** ![HenryAbra](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@HenryAbra](https://forums.developer.nvidia.com/u/HenryAbra)\
**Post date:** [January 8, 2008, 3:43pm UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/11 "2008-01-08T15:43:25Z")

</div>

Thank you for the quick answer. I really appreciate it.

I now have a better understanding about the shared memory mechanism.

Although i still don’t understand something:

I was looking at all projects using shared memory to have a better understanding and in some projects i find this kind of shared memory allocation:

> [@](#):
>
> **global** static void bitonicSort(int \* values)
> 
> {
> 
> **extern shared int shared;**
> 
> const int tid = threadIdx.x;
> 
> // Copy input to shared mem.
> 
> shared[tid] = values[tid];
> 
> \_\_syncthreads();
> 
> // Parallel bitonic sort.
> 
> for (int k = 2; k \<= NUM; k \*= 2)
> 
> {
> 
> // Bitonic merge:
> 
> for (int j = k / 2; j\>0; j /= 2)
> 
> {
> 
> int ixj = tid ^ j;
> 
> if (ixj \> tid)
> 
> {
> 
> if ((tid & k) == 0)
> 
> {
> 
> if (shared[tid] \> shared[ixj])
> 
> {
> 
> swap(shared[tid], shared[ixj]);
> 
> }
> 
> }
> 
> else
> 
> {
> 
> if (shared[tid] \< shared[ixj])
> 
> {
> 
> swap(shared[tid], shared[ixj]);
> 
> }
> 
> }
> 
> }
> 
> \_\_syncthreads();
> 
> }
> 
> }
> 
> // Write result.
> 
> values[tid] = shared[tid];
> 
> }

The bold line is the interesting one.

What is the purpose of extern here? Dynamic allocation? What is the size of the memory allocated here?

It says in the manual that all memory allocated this way start in the same address but nothing is said about its size.

I am sorry for my lack of knowledge but i am trying to understand. This parallel processing with shared memory is really tricky.

---

<div class="post-metadata">

**Author:** ![DenisR](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@DenisR](https://forums.developer.nvidia.com/u/DenisR)\
**Post date:** [January 8, 2008, 4:37pm UTC](https://forums.developer.nvidia.com/t/shared-memory-mechanism/2265/12 "2008-01-08T16:37:22Z")

</div>

This memory is allocated outside of the kernel. In the function that is calling the kernel you will see the kernel is called like this :

bitonicSort\<\<\<gridDim,blockDim,shared\_memory\_size\>\>\>(…)
