我正在尝试实现一个异步 PSO。我这样做的方法如下:
__global__ void particle(double *pos, double *pbest, double *vpbest, double *vel, double *gbest){
int thread = threadIdx.x + blockDim.x * blockIdx.x;
int particle, i = 0;
double tpbest;
double l, r;
int index, best, j;
if(thread < DIMPAR){
particle = thread / NDIM;
do{
best = ring(vpbest, &particle);
index = (best * NDIM) + (thread % NDIM);
l = (double) 2.05 * (double) uniform(thread) * ( pbest[thread] - pos[thread] );
r = (double) 2.05 * (double) uniform(thread) * ( pbest[index] - pos[thread] );
vel[thread] = vel[thread] + l + r;
pos[thread] = pos[thread] + vel[thread];
__syncthreads(); // I am trying wait all threads write in global memory
if( (thread % NDIM) == 0 ){ //only one thread replace the vector
tpbest = rastrigin(pos, particle * NDIM, NDIM);
if(tpbest < vpbest[particle]){
vpbest[particle] = tpbest;
for(j = 0 ; j < NDIM; j++){
pbest[(particle * NDIM) + j] = pos[(particle * NDIM) + j];
}
}
}
i++;
}while(i < 10000);
}
}
电话:
particle<<<1,512>>>(d_pos, d_pbest, d_vpbest, d_velo, d_gbest);
有时同步会出现问题... pos[thread] 中的某些值会发散。在 B.6 节 CUDA_C_PROGRAMMING 指南中:
等待直到线程块中的所有线程都达到这一点,并且这些线程在 __syncthreads() 之前进行的所有全局和共享内存访问对块中的所有线程都是可见的。
pos向量是这样的:
p0 = [0,1,2] //粒子 1
p1 = [3,4,5] //粒子 2
p2 = [6,7,8] //粒子 3
pos = [1,2,3,4,5,6,7,8] //pos向量,DIMPAR = 9; NPAR = 3;NDIM = 3
当我使用 NDIM >= 30 时,会发生分歧
如何使用全局内存确保同步?