【发布时间】:2015-09-04 17:02:39
【问题描述】:
Cuda printf 似乎不尊重 __syncthreads(),即使在同一个块中也是如此。特别是,我希望如果我的线程在调用 __syncthreads 之前打印出一些东西,然后在调用之后打印出其他东西,那么我会看到所有之前的打印,然后是所有的之后的打印。这不是我所看到的,我想知道我是否遗漏了什么。这是我的代码示例:
#include <stdio.h>
#include <cuda_runtime_api.h>
#define ROUND_UP(x) (((x)&1) + ((x)>>1))
__global__ void test()
{
int t = threadIdx.x, last = blockDim.x;
int offset = ROUND_UP(last);
while (last > 1 && t + offset < last) {
offset = ROUND_UP(offset);
last = ROUND_UP(last);
__syncthreads();
if (t == 33 || t == 64)
printf("A: t = %d, last = %d\n", t, last);
}
while (last > 1) {
last = ROUND_UP(last);
__syncthreads();
if (t == 33 || t == 64)
printf("B: t = %d, last = %d\n", t, last);
}
}
int main()
{
test<<<1,66>>>();
cudaDeviceSynchronize();
return 0;
}
这会产生以下输出:
B: t = 64, last = 33
B: t = 64, last = 17
B: t = 33, last = 33
B: t = 64, last = 9
B: t = 33, last = 17
B: t = 64, last = 5
B: t = 33, last = 9
B: t = 64, last = 3
B: t = 33, last = 5
B: t = 64, last = 2
B: t = 33, last = 3
B: t = 64, last = 1
B: t = 33, last = 2
B: t = 33, last = 1
当我读到这篇文章时,线程 64 在线程 33 第二次进入之前已经退出了 __syncthreads 两次。这怎么可能?
【问题讨论】:
-
您在依赖于 threadIdx 的条件块中使用同步线程。我怀疑你的代码可能在这方面被破坏了。
-
@Robert,构造循环的目的是不管threadIdx如何,同步线程都将被调用相同的次数。 ROUND_UP 宏将其输入减半,向上取整,因此 last 从 66、33、17、9、5、3、2、1 开始。每次调用一次 synthreads,尽管调用它的 while 循环因线程而异idx.
-
@JonathanShaw:抱歉,在手机屏幕上很难找到。请记住,CUDA 中的内存事务是“即发即弃”,并且内存控制器清除事务请求的顺序是未定义的,这可能会影响您看到的顺序。一般来说,可能不建议您尝试使用 printf 的方式
-
那么您只是在猜测这是使用
__syncthreads()的有效方法吗?如果您阅读 the documentation,我想您会发现“条件代码中允许使用 __syncthreads(),但前提是条件在整个线程块中的计算结果相同”。在我看来,您的情况在整个线程块中的评估结果并不相同。也许你应该在你的代码中使用 synccheck 选项运行 cuda-memcheck。 -
@talonmies,我希望来自不同线程的打印以随机顺序出现,但你是说我不应该期望这个顺序会正确尊重同步线程?