Hi All,
Consider this [multi-threaded] code fragment...
I'm trying to throttle the number of pthreads accessing this bit of code. The mutexes are initialised and destroyed elsewhere.Code:int volatile num_threads = 0; snip... if(num__threads < MAX_NUM_THREADS) { //mutex pthread_mutex_lock(&my_thread_mutex); //increment number of used threads num_threads++; pthread_mutex_unlock(&my_thread_mutex); //mutex printf("%d:DEBUG: num threads = %d\n",pthread_self(),num_threads); //do work if(do_work() < 0) { //mutex pthread_mutex_lock(&my_thread_mutex); //decrement number of slaves num_threads--; pthread_mutex_unlock(&my_thread_mutex); //mutex return 1; } //mutex pthread_mutex_lock(&my_thread_mutex); //decrement number of slaves num_threads--; pthread_mutex_unlock(&my_thread_mutex); //mutex return 0; }
The problem is that num_threads ends up negative i..e somehow the decrement is happening more than the increment.
Can anyone see why?
Are my mutexes used correctly?
Thanks for any help,
rotis23