Advertisement
Guest User

Untitled

a guest
May 25th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // Ensures that all threads have completed the lines before this before
  4. // passing this point. Note that `n` *MUST* be 1 on the 1st invocation
  5. // within `foreach_thread`, 2 on the 2nd, 3 on the 3rd, and so on.
  6. // Otherwise, the behavior is undefined.
  7. #define syncthreads(n) break; case n:
  8.  
  9. // Runs the code on `blockDim` threads. Undefined execution order should be
  10. // assumed unlesss `syncthreads` is used, in which case it is guarenteed all
  11. // threads complete what's above before running what's below. In practice,
  12. // each thread will run sequentially between `syncthreads` calls.
  13. #define foreach_thread(blockDim, unbraced_code) ({\
  14. for (unsigned __computation_index = 0;; __computation_index++) {\
  15. for (unsigned threadIdx_x = 0; threadIdx_x < blockDim; threadIdx_x++) {\
  16. switch (__computation_index) {\
  17. case 0: unbraced_code break;\
  18. default: goto done;\
  19. }\
  20. }\
  21. }\
  22. done:;\
  23. })
  24.  
  25. int main(int argc, char *argv[]) {
  26.  
  27. // Tadah! Just don't try to use local variables or anything...
  28. foreach_thread(3,
  29. printf("Hello from thread %i!\n", threadIdx_x);
  30. printf("I'm still here from thread %i!\n", threadIdx_x);
  31. syncthreads(1);
  32. printf("How are you from thread %i!\n", threadIdx_x);
  33. syncthreads(2);
  34. printf("Bye from thread %i!\n", threadIdx_x);
  35. );
  36.  
  37. /* Output:
  38. Hello from thread 0!
  39. I'm still here from thread 0!
  40. Hello from thread 1!
  41. I'm still here from thread 1!
  42. Hello from thread 2!
  43. I'm still here from thread 2!
  44. How are you from thread 0!
  45. How are you from thread 1!
  46. How are you from thread 2!
  47. Bye from thread 0!
  48. Bye from thread 1!
  49. Bye from thread 2!
  50. */
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement