/* L-26 MCS 572 Wednesday 15 March 2006 : using threads, save as "buffer.c".
 * Compile this example on copper as "cc_r -o buffer buffer.c"
 * and run it like "buffer 3 5 1". */

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

void *get_next ( void *n );
/* 
 * DESCRIPTION :
 *   Returns a buffer with the next n elements. */

int main ( int argc, char *argv[] )
{
   int i,j,n,next_n;
   int *buffer;
   char ans;
   pthread_t t;

   for(i=1; i<argc; i++)
   {
      n = atoi(argv[i]);

      if(i==1)
         buffer = (int*)get_next((void*)&n);
      else
         pthread_join(t,(void **)&buffer);

      if(i<argc-1)
      {
         next_n = atoi(argv[i+1]);
         pthread_create(&t,NULL,get_next,(void*)&next_n);
      }

      printf("buffer : ");
      for(j=0; j<n; j++)
         printf(" %d",buffer[j]);
      printf("\n");

      printf("press enter to continue");
      scanf("%c",&ans);  /* skip end of line */
      free(buffer);
   }
   return 0;
}

void *get_next ( void *n )
{
   static int nb = 0;
   int i,*b,*k;

   k = (int*)n;

   b = (int*)calloc(*k,sizeof(int));

   for(i=0; i<*k; i++) b[i] = ++nb;

   return (void*)b;
}
