Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- // Ensures that all threads have completed the lines before this before
- // passing this point. Note that `n` *MUST* be 1 on the 1st invocation
- // within `foreach_thread`, 2 on the 2nd, 3 on the 3rd, and so on.
- // Otherwise, the behavior is undefined.
- #define syncthreads(n) break; case n:
- // Runs the code on `blockDim` threads. Undefined execution order should be
- // assumed unlesss `syncthreads` is used, in which case it is guarenteed all
- // threads complete what's above before running what's below. In practice,
- // each thread will run sequentially between `syncthreads` calls.
- #define foreach_thread(blockDim, unbraced_code) ({\
- for (unsigned __computation_index = 0;; __computation_index++) {\
- for (unsigned threadIdx_x = 0; threadIdx_x < blockDim; threadIdx_x++) {\
- switch (__computation_index) {\
- case 0: unbraced_code break;\
- default: goto done;\
- }\
- }\
- }\
- done:;\
- })
- int main(int argc, char *argv[]) {
- // Tadah! Just don't try to use local variables or anything...
- foreach_thread(3,
- printf("Hello from thread %i!\n", threadIdx_x);
- printf("I'm still here from thread %i!\n", threadIdx_x);
- syncthreads(1);
- printf("How are you from thread %i!\n", threadIdx_x);
- syncthreads(2);
- printf("Bye from thread %i!\n", threadIdx_x);
- );
- /* Output:
- Hello from thread 0!
- I'm still here from thread 0!
- Hello from thread 1!
- I'm still here from thread 1!
- Hello from thread 2!
- I'm still here from thread 2!
- How are you from thread 0!
- How are you from thread 1!
- How are you from thread 2!
- Bye from thread 0!
- Bye from thread 1!
- Bye from thread 2!
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement