home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / mach / doc / unpublished / examples / masterslave.c.Z / masterslave.c
Encoding:
C/C++ Source or Header  |  1989-12-21  |  2.0 KB  |  81 lines

  1. /*
  2.  * This program is an example of a master thread spawning a number of 
  3.  * concurrent slaves.  The master thread waits until all of the slaves have
  4.  * finished to exit.  Once created a slave process doesn't do much in this
  5.  * simple example except loop.  A count variable is used by the master and
  6.  * slave processes to keep track of the current number of slaves executing.
  7.  * A mutex is associated with this count variable, and a condition variable
  8.  * with the mutex.  This program is a simple demonstration of the use of
  9.  * mutex and condition variables.
  10.  */
  11.  
  12. #include <stdio.h>
  13. #include <cthreads.h>
  14.  
  15. int count;         /* number of slaves active */
  16. mutex_t lock;      /* mutual exclusion for count */
  17. condition_t done;  /* signalled each time a slave finishes */
  18.  
  19. extern long random();
  20.  
  21. init()
  22. {
  23.     cthread_init();
  24.     count = 0;
  25.     lock = mutex_alloc();
  26.     done = condition_alloc();
  27.     srandom(time((int *) 0));  /* initialize random number generator */
  28. }
  29.  
  30. /*
  31.  * Each slave just counts up to its argument, yielding the processor on 
  32.  * each iteration.  When it is finished, it decrements the global count
  33.  * and signals that it is done.
  34.  */
  35. slave(n)
  36.     int n;
  37. {
  38.     int i;
  39.  
  40.     for (i = 0; i < n; i += 1)
  41.         cthread_yield();
  42.     mutex_lock(lock);
  43.     count -= 1;
  44.     printf("Slave finished %d cycles.\n", n);
  45.     condition_signal(done);
  46.     mutex_unlock(lock);
  47. }
  48.  
  49. /*
  50.  * The master spawns a given number of slaves and then waits for them all to 
  51.  * finish.
  52.  */
  53. master(nslaves)
  54.     int nslaves;
  55. {
  56.     int i;
  57.  
  58.     for (i = 1; i <= nslaves; i += 1) {
  59.         mutex_lock(lock);
  60.         /*
  61.          * Fork a slave and detach it,
  62.          * since the master never joins it individually.
  63.          */
  64.         count += 1;
  65.         cthread_detach(cthread_fork(slave, random() % 1000));
  66.         mutex_unlock(lock);
  67.     }
  68.     mutex_lock(lock);
  69.     while (count != 0)
  70.         condition_wait(done, lock);
  71.     mutex_unlock(lock);
  72.     printf("All %d slaves have finished.\n", nslaves);
  73.     cthread_exit(0);
  74. }
  75.  
  76. main()
  77. {
  78.     init();
  79.     master((int) random() % 16);  /* create up to 15 slaves */
  80. }
  81.