#include #include #include using namespace std; // A demo of pthreads. #define NUM_THREADS 4 // print a countdown void *countdown(void* arg) { int thread_id = *((int*) arg); cout << "started thread " << thread_id << endl; for (int count = 0; count <= 10; count++) { sleep(1); // sleep for 1 second cout << "thread " << thread_id << ": " << count << endl; } cout << "finished thread " << thread_id << endl; return NULL; } // create a set of threads to run simultaneous countdowns int main() { cout << "main thread starting" << endl; pthread_t threads[NUM_THREADS]; // array of thread objects // create threads for (int tid = 0; tid < NUM_THREADS; tid++) { // create a thread and have it execute the countdown function if (pthread_create(&threads[tid], NULL, countdown, &tid)) { cout << "Error creating thread" << endl; } usleep(200000); // sleep for 200 ms } // wait for threads to finish for (int tid = 0; tid < NUM_THREADS; tid++) { /* if (pthread_join(threads[tid], NULL)) { cout << "Error joining thread" << endl; } */ } cout << "main thread exiting" << endl; return 0; }