/* Simple pthread test.  Create 'n' threads that spin and wait
 * for them to return. */

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

#define MAX_NUM_THREADS 128
#define LOOPS 1024
void *simple_thread(void *arg) {
    int i, n = (int)arg;
    pthread_t t = pthread_self();

    for(i=0; i<LOOPS; i++) {
	printf("simple_thread(%d): tid=0x%x, i=%d\n", n, t, i);
    }

    return (void *)n;
}

int main(int argc, char *argv[]) {
    pthread_t thread[MAX_NUM_THREADS];
    pthread_attr_t attr[MAX_NUM_THREADS];
    int i, r;
    void *thread_ret_val[MAX_NUM_THREADS];
    unsigned num_threads = 2;

    if (argc > 1) {
	num_threads = strtoul(argv[1], NULL, 0);
    }
    printf("pthread_test(): Creating %d threads.\n", num_threads);

    /* Init threads */
    for(i=0; i<num_threads; i++) {
	r = pthread_attr_init(&attr[i]);
	if (r < 0) {
	    perror("pthread_attr_init()");
	    return -1;
	}
    }

    /* Create threads */
    for(i=0; i<num_threads; i++) {
	r = pthread_create(&thread[i], &attr[i], simple_thread, (void *)i);
	if (r < 0) {
	    perror("pthread_create()");
	    return -1;
	}
    }

    /* Wait for threads */
    for(i=0; i<num_threads; i++) {
	r = pthread_join(thread[i], &thread_ret_val[i]);
	if (r < 0) {
	    perror("pthread_create()");
	    return -1;
	}
	printf("thread %d return value: 0x%08x\n", 
	       i, (int)thread_ret_val[i]);
    }

    return 0;
}

