如何在OpenCL中向数组末尾添加元素?

时间:2016-10-02 16:38:06

标签: c multithreading parallel-processing opencl gpgpu

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

安全地说,我的意思是没有并发问题,比如一个线程试图在同一个地方添加一个元素作为另一个元素

1 个答案:

答案 0 :(得分:0)

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

/*
 * 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];
}