I am working on a multi-threaded app that converts files. I want it to launch a new thread for each conversion, up to the available number of CPU cores. To keep track of how many threads are already running, I keep a global variable that is decremented by each thread once it's finished. To make sure there aren't any problems by more than one thread trying to update this variable simultaneously, I use a mutex. However, I'm not exactly sure how it works.
I assume that when creating a mutex, the common pthread_mutex_t variable must be seen by any part of the code that attempts to read/write the variable in question. So, what I've done is initialized the mutex on the main thread, then passed a pointer to it to each of the threads. The code isn't comprehensive, but hopefully you'll get what I'm trying to do:
Does this make sense?Code:#define MAX_THREADS 4 int counter; //thread counter void *threadFunction(void *mutex){ pthread_mutex_t *mutex_t = mutex; //do thread stuff //decrement counter pthread_mutex_lock(&(*mutex_t)); counter--; pthread_mutex_unlock(&(*mutex_t)); } int main(){ counter = 0; pthread_mutex_t mutex; pthread_t thread_id = 1; pthread_mutex_init(&mutex, NULL); pthread_create(&thread_id, NULL, threadFunction, (void*)&mutex); counter++; //check counter to see if more threads can start pthread_mutex_lock(&mutex); if(counter>MAX_THREADS){ //wait code } pthread_mutex_destroy(&mutex); return 0; }



LinkBack URL
About LinkBacks




