在CUDA中分配共享变量 [英] Allocate shared variables in CUDA

查看:132
本文介绍了在CUDA中分配共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在CUDA中分配共享变量?我有一个内核,需要在属于特定块的线程之间共享数据。我需要两个名为 sid eid 的共享变量。我这样使用它:

How to allocate shared variables in CUDA? I have a kernel where data needs to be shared across threads belonging to a particular block. I need two shared variables named sid and eid. I use it like this:

extern __shared__ int sid, eid  

但它给我一个错误,即 __ shared __ 变量不能具有外部链接。

but it is giving me an error that __shared__ variables cannot have external linkage.

推荐答案

分配共享内存有两种方法:静态和动态

There are two ways to allocate shared memory : static and dynamic

1,静态

  __shared__ int Var1[10]

2,动态:应添加 extern关键字

2、dynamic : should add "extern" keyword

extern __shared__ int Var1[]

如果您使用动态方式分配共享内存,您应在调用函数时设置共享内存的大小。例如:

testKernel<<<网格,线程,大小>>>(...)

第三个参数是共享内存的大小。这样,所有共享内存都从同一地址开始。因此,如果您想定义几个共享内存。您应该编写如下代码。

If you use dynamic way to allocate shared memory, you should set the shared memory size when you call the function. for example:
testKernel <<< grid, threads, size>>>(...)
the third para is the size of shared memory. In this way All the shared memories start from the same address. so if you want to define several shared memories. you should write code like following.

__global__ void func(...)
{
    extern __shared__ char array[];
    short * array0 = (short*)array;
    float * array1 = (float*)(&array0[128]);
}

这篇关于在CUDA中分配共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆