比较CUDA中两个线程之间的值

比较CUDA中两个线程之间的值,cuda,synchronization,comparison,Cuda,Synchronization,Comparison,假设一个块中的所有线程都有一个整数变量a,该变量的值在线程之间可能不同。如何比较块中的第一个线程是否与块中的最后一个线程具有相同的a?我只需要比较这两个线程,因为a的值不会随着线程索引而减少。这里有一个解决方案,其中块包含的扭曲超过一个,您必须使用共享内存或全局内存,共享内存将更快。 静态共享内存可以在已知大小的情况下使用: // .. thread_block block = this_thread_block(); __shared__ int s[2]; __shared__ bool

假设一个块中的所有线程都有一个整数变量
a
,该变量的值在线程之间可能不同。如何比较块中的第一个线程是否与块中的最后一个线程具有相同的
a
?我只需要比较这两个线程,因为
a
的值不会随着线程索引而减少。

这里有一个解决方案,其中块包含的扭曲超过一个,您必须使用共享内存或全局内存,共享内存将更快。 静态共享内存可以在已知大小的情况下使用:

// .. 
thread_block block = this_thread_block();
__shared__ int s[2];
__shared__ bool result;
uint32_t tid = threadIdx.x;

if(tid == 0)
    s[0] = a;
if(tid == blockDim.x - 1)
    s[1] = a;
block.sync(); // synchronize the block instead the whole grid

if(tid == 0)
    result = s[0] == s[1];
block.sync();
如果块只有一个扭曲,或者如果必须比较扭曲的第一个和最后一个线程的
a
,则使用

#包括
名称空间cg=协作组;
自动激活=cg::联合_线程();
int theOtherA=active.shfl(a,active.size()-1);//每个人都有一份
//经纱的最后一根线
bool result=a==theOtherA;//线程0具有正确的结果
结果=活动。shfl(结果,0);//从线程0的寄存器中获取副本

只要有两个共享内存字,每个字都存储其值,然后让一个threas比较存储在两个位置的值?块大小是多少?@Oblivion,它是256个线程。@SergeRogatch我认为最好的选择是talonmies当时建议的。如果你的区块中只有一个扭曲,有一个更好的解决方案
#include <cooperative_groups.h>
namespace cg = cooperative_groups;

auto active = cg::coalesced_threads();
int theOtherA = active.shfl(a, active.size() -1); // everybody has a copy a from 
//last thread of the warp
bool result = a == theOtherA; // thread 0 has correct result
result = active.shfl(result, 0); // get a copy from the register of thread 0