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

#define MAXTHREADS  10
#define MAXITEMS    1000

struct {
     FILE *outfp;
     int nitems;
     int nthreads;
} shared;

void *simple(void *a)
{
     int m, tnum, inum;

     inum = shared.nitems / shared.nthreads;
     tnum = *(int *)a;

     for (m=0; m<inum; m++)
          fprintf(shared.outfp, "Thread: %d\tItem: %d\n", tnum, m);

     return(NULL);
}

int main(int argc, char *argv[])
{
     int i;
     pthread_t tid[MAXTHREADS];

     if ((shared.outfp = fopen("thread_outputs.txt", "w")) == NULL) {
          fprintf(stderr, "Cannot open thread_outputs.txt file for writing\n");
          exit(1);
     }

     shared.nitems = atoi(argv[1]) % MAXITEMS;
     shared.nthreads = atoi(argv[2]) % MAXTHREADS;

     for (i=0; i<shared.nthreads; i++)
          pthread_create(&tid[i], NULL, simple, (void *)&i);

     for (i=0; i<shared.nthreads; i++)
          pthread_join(tid[i], NULL);

     printf("Done!\n");
     fclose(shared.outfp);
     exit(0);
}

     
          
