【发布时间】:2013-11-07 15:40:48
【问题描述】:
所以,我最近开始了 CUDA 编程。
我尝试制作一个启动多个线程的程序,进入一组全局内存及其启动顺序。
但是,部分独占控制似乎效果不佳。
我想防止多个线程同时访问数组Log。
现在,数组Log是这样的。
Log[0]=160
Log[1]=128
Log[2]=256
Log[3]=96
Log[4]=0
Log[5]=0
Log[6]=0
...etc
我要防止多个线程同时访问独占控制的内存数组Log。
是不是做错了怎么使用“__threadfence()”的?
我用的是CUDA5.5,计算能力是2.1。
请建议某人。
以下是源代码。
#include <cuda_runtime.h>
#include <stdio.h>
#include <cuda.h>
#include <cstdio>
#include <thrust/device_ptr.h>
#define N 256
//Prototype declaration
__global__ void CudaThreadfenceTest(int *Log_d);
int main(){
int i,j;
int Log[N];
int *Log_d;
//
for(j=0;j<N;j++){
Log[j]=0;
}
// GPU memory hold
cudaMalloc((void**)&Log_d, N*sizeof(int));
// host→device
cudaMemcpy(Log_d,Log,N*sizeof(int),cudaMemcpyHostToDevice);
/*****************
*block & thread
******************/
dim3 blocks(1,1,1);
dim3 threads(256,1,1);
//run kernel
CudaThreadfenceTest<<<blocks,threads>>>(Log_d);
cudaDeviceSynchronize();
cudaMemcpy(Log,Log_d,N*sizeof(int),cudaMemcpyDeviceToHost);
for(j=0;j<N;j++){
printf("Log[ %d ]=%d \n",j,Log[j]);
}
getchar();
cudaFree(Log_d);
return 0;
}
/*************************
/* kernel
/*************************/
__global__ void CudaThreadfenceTest(int *Log_d){
printf("threadIdx.x = %d , \n",threadIdx.x);
__threadfence();
//for Log
for(int j=0;j<N;j++){
if(Log_d[j]==0){
Log_d[j]=threadIdx.x + 1;
break;
}
}
}
【问题讨论】:
标签: c++ c visual-studio-2010 cuda nvidia