// thread1.cpp
// Glenn G. Chappell
// 6 Feb 2012
//
// For CS 321 Spring 2012
// Basic pThreads Demo

#include <pthread.h>  // *ix: compile with -lpthread
#include <unistd.h>   // for _exit
#include <iostream>
using std::cout;
using std::endl;

const int NUMTHREADS = 5;  // Number of threads to spawn

pthread_t pt[NUMTHREADS];  // threads[i] is pthread_t structure
                           //  for thread #i

int threadsdone = 0;       // Number of spawned threads that have
                           //  finished, so far


// runThread
// Function that new threads execute
// Parameter is (int *) pointing to thread number (0, 1, ...)
// Return value not used
void * runThread(void * x)
{
    // Get thread number & output it
    int param = *(int *)(x);
    cout << "This is thread #" << param << endl;

    // Say "I'm done" by incrementing finished-thread count
    ++threadsdone;

    return 0;  // NULL pointer
}

int main()
{
    int params[NUMTHREADS];  // params[i] is param for function
                             //  runThread for thread #i

    // Make threads
    for (int i = 0; i < NUMTHREADS; ++i)
    {
        params[i] = i;
        int err = pthread_create(&pt[i], 0, runThread, &params[i]);
        if (err)
        {
            cout << "Failed to create thread " << i << endl;
            _exit(1);
        }
    }

    // Wait for threads to finish
    // (This might be problematic ...)
    while (threadsdone != NUMTHREADS) ;
    cout << "All slave threads exited; done" << endl;

    return 0;  // Success
}

