/* Demonstrate Thread Creating and Exiting */ /* Demonstrate use of condition variable */ /* George F. Riley. ECE3055, Spring 2003 */ #include #include #include #define N_THREAD 5 /* Mutex and condition variable for exit notification */ pthread_mutex_t DoneMutex; pthread_cond_t DoneCond; int DoneCount; void* Philosopher ( int IntIndex ) { printf("Hello from Philosopher %d\n", IntIndex); pthread_mutex_lock(&DoneMutex); DoneCount++; if (DoneCount == N_THREAD) { pthread_cond_signal(&DoneCond); // Signal to main that all are done } pthread_mutex_unlock(&DoneMutex); printf("Exit from Philosopher %d\n", IntIndex); return ((void*)IntIndex); } int main(int argc, char** argv) { int i; pthread_t t[N_THREAD]; pthread_mutex_init(&DoneMutex, NULL); pthread_cond_init(&DoneCond, NULL); /* This is important! */ pthread_mutex_lock(&DoneMutex); /* Why did we lock this BEFORE thread creation? */ for (i = 0; i < N_THREAD; i++) { printf("Creating thread %d\n", i); pthread_create(&t[i], NULL, (void*(*)(void*))Philosopher, (void*)i); pthread_detach(t[i]); } pthread_cond_wait(&DoneCond, &DoneMutex); printf("Got condition signal\n"); pthread_mutex_unlock(&DoneMutex); return (0); } #ifdef HERES_THE_OUTPUT Creating thread 0 Creating thread 1 Creating thread 2 Creating thread 3 Hello from Philosopher 0 Hello from Philosopher 1 Hello from Philosopher 2 Creating thread 4 Hello from Philosopher 3 Hello from Philosopher 4 Exit from Philosopher 0 Exit from Philosopher 1 Exit from Philosopher 2 Exit from Philosopher 3 Got condition signal Exit from Philosopher 4 #endif