/* L-27 MCS 572 Friday 17 March 2006 : manager/workers with threads.
 * Compile this example on copper as "cc_r -o workers workers.c"
 * and run it typing "workers" at the prompt. */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *is_prime ( void *n );
/* 
 * DESCRIPTION :
 *   Returns 0 if n is a prime,
 *   otherwise a divisor of n is returned. */

int main ( int argc, char *argv[] )
{
   int *d,p;

   d = (int*)calloc(1,sizeof(int));
   printf("Give the number of workers : "); scanf("%d",&p);
   {
      pthread_t t[p];
      int i,n[p];

      for(i=0; i<p; i++)
      {
         printf("Give a natural number : "); scanf("%d",&n[i]);
         pthread_create(&t[i],NULL,is_prime,(void*)&n[i]);
      }
      for(i=0; i<p; i++)
      {
         pthread_join(t[i],(void **)&d);
         if(*d == 0)
            printf("The number %d is a prime number.\n",n[i]);
         else
            printf("The number %d is divisible by %d.\n",n[i],*d);
      }
   }
   return 0;
}

void *is_prime ( void *n )
{
   int *nb = (int*)n;
   int i;
   int *d = (int*)calloc(1,sizeof(int));

   for(i=2; i<*nb; i++)
      if((*nb)%i == 0)
      {  
         *d = i;
         return (void*)d;
      }
   *d = 0;
   return (void*)d;
}
