/* ==== test_switch.c ============================================================
 * Copyright (c) 1993 by Chris Provenzano, proven@athena.mit.edu
 *
 * Description : Test context switch functionality.
 *
 *  1.00 93/08/04 proven
 *      -Started coding this file.
 */

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

char *buf = "abcdefghijklimnopqrstuvwxyz";
int fd = 1;
static int n = 0;
static pthread_mutex_t mutex;
static pthread_cond_t cond;

void* new_thread(void* arg)
{
        int j;
	char* buf = malloc(132);
	for (j=0; j<100; j++)
          printf("%c", ((int) arg % 20) + 'a');
	free(buf);
        pthread_mutex_lock(&mutex);
        if (--n==0)
         pthread_cond_broadcast(&cond);
	pthread_mutex_unlock(&mutex);
	pthread_exit(0);
}

main()
{
	int i, count = 10;
	pthread_t* thread;
        int j, k;

	pthread_init();
        thread = (pthread_t*)malloc(count*sizeof(pthread_t));
        pthread_mutex_init(&mutex, 0);
	pthread_cond_init(&cond, 0);
        for (k=0; k<count; k++)
	{
          n = count;
    	  for(i = 0; i < count; i++) {
		if (pthread_create(&thread[i], NULL, new_thread, i)) {
			printf("error creating new thread %d\n", i);
			exit(1);
		}
	  }
	 pthread_mutex_lock(&mutex);
         while (n > 0)
          pthread_cond_wait(&cond, &mutex); 
	 pthread_mutex_unlock(&mutex);
	 for (i=0; i<count; i++)
                pthread_join(thread[i], 0);
	}
	pthread_exit(NULL);
	fprintf(stderr, "pthread_exit returned\n");
	exit(1);
}
