C   130
print tree
Guest on 14th March 2023 12:18:19 AM


  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. /* tree broadcast routine:
  5.  * 0 -(gen=1)-> 1
  6.  *
  7.  * 0 -(gen=2)-> 2
  8.  * 1 -(gen=2)-> 3
  9.  *
  10.  * 0 -(gen=4)-> 4
  11.  * 1 -(gen=4)-> 5
  12.  * 2 -(gen=4)-> 6
  13.  * 3 -(gen=4)-> 7
  14.  * ...
  15.  *
  16.  * In gen, processes (gen <= rank < 2*gen) will receive the broadcast data.
  17.  */
  18. int main(int argc, char *argv[])
  19. {
  20.         int gen, rank, size;
  21.         int to, from;
  22.  
  23.         /* scan over a hypothetical virtual machine of 15 nodes */
  24.         size = 15;
  25.         for (rank = 0; rank < size; rank++) {
  26.                 printf("rank %d", rank);
  27.  
  28.                 /* gen reflects the generation (depth) in the tree broadcast */
  29.                 gen = 1;
  30.                 while (gen < size) {
  31.                         if (rank >= 2 * gen) {  /* wait for the data to come out */
  32.                                 printf("\t");
  33.                         } else if (rank >= gen && rank < 2 * gen) {     /* receive message */
  34.                                 from = rank - gen;
  35.                                 printf("\tfrom %d", from);
  36.                         } else if (rank < gen) {        /* send message */
  37.                                 to = rank + gen;
  38.                                 if (to < size)
  39.                                         printf("\tto %d", to);
  40.                         }
  41.                         gen *= 2;
  42.                 }
  43.  
  44.                 /* done for a given rank */
  45.                 printf("\n");
  46.         }
  47. }

Raw Paste

Login or Register to edit or fork this paste. It's free.