|
| 1 | +#include <stdio.h> |
| 2 | + |
| 3 | +__global__ void staticReverse(int *d, int n) |
| 4 | +{ |
| 5 | + __shared__ int s[64]; |
| 6 | + int t = threadIdx.x; |
| 7 | + int tr = n-t-1; |
| 8 | + s[t] = d[t]; |
| 9 | + __syncthreads(); |
| 10 | + d[t] = s[tr]; |
| 11 | +} |
| 12 | + |
| 13 | +__global__ void dynamicReverse(int *d, int n) |
| 14 | +{ |
| 15 | + extern __shared__ int s[]; |
| 16 | + int t = threadIdx.x; |
| 17 | + int tr = n-t-1; |
| 18 | + s[t] = d[t]; |
| 19 | + __syncthreads(); |
| 20 | + d[t] = s[tr]; |
| 21 | +} |
| 22 | + |
| 23 | +int main(void) |
| 24 | +{ |
| 25 | + const int n = 64; |
| 26 | + int a[n], r[n], d[n]; |
| 27 | + |
| 28 | + for (int i = 0; i < n; i++) { |
| 29 | + a[i] = i; |
| 30 | + r[i] = n-i-1; |
| 31 | + d[i] = 0; |
| 32 | + } |
| 33 | + |
| 34 | + int *d_d; |
| 35 | + cudaMalloc(&d_d, n * sizeof(int)); |
| 36 | + |
| 37 | + // run version with static shared memory |
| 38 | + cudaMemcpy(d_d, a, n*sizeof(int), cudaMemcpyHostToDevice); |
| 39 | + staticReverse<<<1,n>>>(d_d, n); |
| 40 | + cudaMemcpy(d, d_d, n*sizeof(int), cudaMemcpyDeviceToHost); |
| 41 | + for (int i = 0; i < n; i++) |
| 42 | + if (d[i] != r[i]) printf("Error: d[%d]!=r[%d] (%d, %d)\n", i, i, d[i], r[i]); |
| 43 | + |
| 44 | + // run dynamic shared memory version |
| 45 | + cudaMemcpy(d_d, a, n*sizeof(int), cudaMemcpyHostToDevice); |
| 46 | + dynamicReverse<<<1,n,n*sizeof(int)>>>(d_d, n); |
| 47 | + cudaMemcpy(d, d_d, n * sizeof(int), cudaMemcpyDeviceToHost); |
| 48 | + for (int i = 0; i < n; i++) |
| 49 | + if (d[i] != r[i]) printf("Error: d[%d]!=r[%d] (%d, %d)\n", i, i, d[i], r[i]); |
| 50 | +} |
0 commit comments