【问题标题】:How to pause all CUDA threads until thread 0 finished some code?如何暂停所有 CUDA 线程,直到线程 0 完成一些代码?
【发布时间】:2021-06-07 10:54:27
【问题描述】:

我在下面有一个简单的 CUDA 代码。我的问题是如何在线程 0 初始化数组数据时使所有线程暂停。所以在那之后,所有线程都可以访问数据中的元素。

__device__ int *data;

__global__ void test() {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;

    if (idx == 0) {
        data = (int *) malloc(10 * sizeof (int));
    }

    data[idx] = idx;
    printf("%d", data[idx]);
}

int main() {
    test << <1, 10 >> >();
    return 0;
}

【问题讨论】:

    标签: cuda


    【解决方案1】:

    CUDA 提供的唯一方法是通过cooperative groups grid synchronization 来执行此操作(在一般情况下,内核启动有超过 1 个块)。 This answer 提供了一个使用协作组网格范围同步的示例。

    由于使用协作组非常复杂,您可能需要考虑在启动内核之前仅在主机代码中初始化此指针。 This answer 展示了如何做到这一点。

    在您的特定情况下,您只启动一个块,您可以使用__syncthreads()

    if (idx == 0) {
        data = (int *) malloc(10 * sizeof (int));
    }
    __syncthreads();
    data[idx] = idx;
    printf("%d", data[idx]);
    

    【讨论】:

    • 完美。非常感谢@Robert Crovella。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多