I'm having trouble understanding condition variables like pthread_mutex_lock
/unlock
and pthread_cond_wait
/signal
I'm trying to create nine threads
, and have them all run at the same time to figure out which is the most efficient.
int threadNumber = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
#define NUM_THREADS 9
//used to store the information of each thread
typedef struct{
pthread_t threadID;
int policy;
struct sched_param param;
long startTime;
long taskStartTime;
long endTime1;
long endTime2;
long endTime3;
long runTime;
char startDate[30];
char endDate[30];
}ThreadInfo;
ThreadInfo myThreadInfo[NUM_THREADS];
//main function
int main(void){
printf("running...\n");
pthread_mutex_lock(&mutex); //lock the mutex//////
pthread_cond_wait(&cond, &mutex); //start waiting//////
int fifoPri = 60;
int rrPri = 30;
//create the 9 threads and assign their scheduling policies
for(int i=0; i<NUM_THREADS; i++){
if(i%3 == SCHED_OTHER){
myThreadInfo[i].policy = SCHED_OTHER;
myThreadInfo[i].param.sched_priority = 0;
}
else if (i%3 == SCHED_RR){
myThreadInfo[i].policy = SCHED_RR;
myThreadInfo[i].param.sched_priority = rrPri++;
}
else{
myThreadInfo[i].policy = SCHED_FIFO;
myThreadInfo[i].param.sched_priority = fifoPri++;
}
pthread_create( &myThreadInfo[i].threadID, NULL, ThreadRunner, &myThreadInfo[i]);
}
printf("\n\n");
pthread_mutex_unlock(&mutex) //unlock the mutex/////////
pthread_cond_signal(&cond); //signal the threads to start////////
//join each thread
for(int g = 0; g < NUM_THREADS; g++){
pthread_join(myThreadInfo[g].threadID, NULL);
}
//print out the stats for each thread and perform an analysis of the data
DisplayThreadSchdStats();
return 0;
}
...
so when the main function starts, I lock
the mutex to make sure the threads don't start before I tell them to with pthread_lock(&mutex) and pthread_cond_wait(&cond, &mutex)
then I create all nine threads with various scheduling policies. After that's completely done, I try to tell the threads to all start at the same time using pthread_mutex_unlock(&mutex) and pthread_cond_signal(&cond)
But when I run this, it never unlocks the threads. The main function's "running..." print statement goes off, but the threads never start. (threadrunner has a function where they all print out a ton of different numbers so I can see if they launch). What am I doing wrong with the pthread mutex and pthread cond?
pthread_mutex_*
is the basic blocking mechanism. Thepthread_cond_*
functions are to be used to test arbitrary conditions on a mutex. They depend on a mutex to block, and you need to pass a mutex reference for them to be used.... They are different things.... not different things to implement the same thing. – Luis Colorado