I'm working on a class assignment and looking for hints to help sovle my logic issue.
The code is supposed to create a number of threads that each output and then wait until the predetermined last thread is created and then each thread output again. Execution yields desired results except the last thread doesn't output the the second time. Could someone give me a hint as to what is causing the last thread not to output after the signal is received?
Here is the code, followed by the output executed.
//--------------------------------------------------------
#include <pthread.h>
#include <iostream>
#include <cstdlib>
#define NUM_THREADS 4 // number of threads allowed
using namespace std;
//-----------------------------------------------------
int main(){
pthread_t hungryThd[NUM_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
// create threads
for ( int i = 0; i < NUM_THREADS; i++){
pthread_create(&hungryThd[i],NULL,Restaurant,(void *) i);
}
// join threads
for (int j = 0; j < NUM_THREADS; j++)
pthread_join(hungryThd[j],NULL);
return 0;
}
//-----------------------------------------------------
void waitForOthers(long threadID){
// add barrier and output code here
cout << "I am thread " << threadID << " working on task "
<< taskWhileWaiting << " and waiting to eat." << endl;
taskWhileWaiting++;
totalThreads++;
//block until all threads are here
if (NUM_THREADS > totalThreads){
pthread_cond_wait(¬Full, &mutex);
cout << "I am thread " << threadID << " and I am eating."
<< endl;
}
}
//-----------------------------------------------------
void * Restaurant(void * param){
long thID = (long) param; // thread IDs
pthread_mutex_lock(&mutex);
waitForOthers(thID); // call wait function
if (totalThreads == NUM_THREADS) // all threads are here
pthread_cond_signal(¬Full); // signal them to eat
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
//------------------------------------------------------------------------
OUTPUT:
I am thread 3 working on task A and waiting to eat.
I am thread 2 working on task B and waiting to eat.
I am thread 1 working on task C and waiting to eat.
I am thread 0 working on task D and waiting to eat.
I am thread 3 and I am eating.
I am thread 2 and I am eating.
I am thread 1 and I am eating.