如何获得唯一标识符

如果block只有一维
blockDim.x表示block的总数,
blockIdx.x 表示当前是第几个block

  1. #include<stdio.h>
  2. __global__ void cuda_hello(void)
  3. {
  4. int bid = blockIdx.x;
  5. int tid = threadIdx.x;
  6. int idx = bid*blockDim.x+tid;
  7. printf("idx:[%d], bid:[%d], tid:[%d] Hello World from GPU!\n",idx,bid, tid);
  8. }
  9. int main()
  10. {
  11. int numOfBlocks = 5;
  12. int numOfThreads = 3;
  13. cuda_hello<<<numOfBlocks , numOfThreads>>>();
  14. cudaDeviceReset();
  15. return 0;
  16. }
  1. #include<stdio.h>
  2. __global__ void narcissistic_and_four_leaf_rose_numbers_gpu(void)
  3. {
  4. // ToDo
  5. int bid = blockIdx.x;
  6. int tid = threadIdx.x;
  7. int idx = bid*blockDim.x+tid;
  8. if (idx>=100&&idx<10000){
  9. int tho, hun, ten, ind,i;
  10. i = idx;
  11. tho = i/1000;
  12. hun = i/100;
  13. ten = (i-hun*100)/10;
  14. ind = i%10;
  15. if(tho>0)
  16. {
  17. hun=(i-tho*1000)/100;
  18. ten=(i-tho*1000-hun*100)/10;
  19. ind=i%10;
  20. if(i==tho*tho*tho*tho + hun*hun*hun*hun + ten*ten*ten*ten + ind*ind*ind*ind)
  21. {
  22. printf("%d ", i);
  23. }
  24. }
  25. else
  26. {
  27. if(i==hun*hun*hun + ten*ten*ten + ind*ind*ind)
  28. {
  29. printf("%d ", i);
  30. }
  31. }
  32. }
  33. }
  34. void narcissistic_and_four_leaf_rose_numbers_cpu(int x1, int x2)
  35. {
  36. int tho, hun, ten, ind;
  37. for(int i=x1; i<x2; i++)
  38. {
  39. tho = i/1000;
  40. hun = i/100;
  41. ten = (i-hun*100)/10;
  42. ind = i%10;
  43. if(tho>0)
  44. {
  45. hun=(i-tho*1000)/100;
  46. ten=(i-tho*1000-hun*100)/10;
  47. ind=i%10;
  48. if(i==tho*tho*tho*tho + hun*hun*hun*hun + ten*ten*ten*ten + ind*ind*ind*ind)
  49. {
  50. printf("%d ", i);
  51. }
  52. }
  53. else
  54. {
  55. if(i==hun*hun*hun + ten*ten*ten + ind*ind*ind)
  56. {
  57. printf("%d ", i);
  58. }
  59. }
  60. }
  61. }
  62. int main()
  63. {
  64. int numLowerBound = 100;
  65. int numUpperBound = 10000;
  66. printf("Narcissistic and four-leaf rose numbers from %d to %d (CPU version):\n", numLowerBound, numUpperBound);
  67. narcissistic_and_four_leaf_rose_numbers_cpu(numLowerBound, numUpperBound);
  68. printf("\nNarcissistic and four-leaf rose numbers from %d to %d (GPU version):\n", numLowerBound, numUpperBound);
  69. // ToDo (Tip: call the function narcissistic_and_four_leaf_rose_numbers_gpu)
  70. narcissistic_and_four_leaf_rose_numbers_gpu<<<10,1024>>>();
  71. cudaDeviceReset();
  72. return 0;
  73. }