【问题标题】:How to add elements to end of array in OpenCL?如何在 OpenCL 中将元素添加到数组的末尾?
【发布时间】:2016-10-02 16:38:05
【问题描述】:

如何在 OpenCL 中安全地将元素添加到数组的末尾?

安全,我的意思是不存在并发问题,例如一个线程试图将一个元素添加到另一个元素所在的位置

【问题讨论】:

    标签: c multithreading parallel-processing opencl gpgpu


    【解决方案1】:

    这段代码将使用原子操作将元素从一个数组并行添加到另一个数组以确保安全。

    /*
     * list: is of size some size greater than a, one thread per element of list
     * a: is of size "size", initially 0
     * size: this is the size of array "a", initial value is 0
     * capacity: this is the number of elements allocated for "a"
     */
    __kernel void AddElementsToEndOfArray(
            __global int* list, 
            __global int* a, 
            __global int size,
            __global int capacity)
    {
        local int sz = atomic_add(&(size),1);
        if (sz >= capacity)
            return;
    
        unsigned int i = get_global_id(0);
        a[sz] = list[i];
    }
    

    【讨论】:

    • 这可能行得通,但要考虑以下几点:“同一 warp 中的线程也一起执行内存访问;当两个或多个线程同时写入同一位置时,CUDA 保证一个任意线程将成功。”
    • 我来晚了,但这是什么意思?我认为使用原子操作可以防止并发访问问题?
    猜你喜欢
    • 2013-07-15
    • 2015-04-17
    • 1970-01-01
    • 2013-02-14
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多