I am confused that what should I use either a mutex or a semaphore in my application,basically my application is a multithreaded server programmed using C and Pthreads. In my application one thread has a dependency over the other i.e one thread needs to wait until a condition is met in the other thread. Earlier I was using the While loop to check when the other thread set the condition as true,but While loop consumes CPU cycles needlessly i.e CPU consumption goes upto 100%.
Currently I started using a mutex in my application as follows:
pthread_mutex_lock(&t_data[rc].mutex);
pthread_mutex_unlock(&t_data[rc].mutex);
In one thread I lock the mutex and when the condition is met in the second thread I unlock it in the second thread( I have handled this doing indexing in a structure,in Which along which other items I have kept a mutex field, each thread is assigned an index when a new client makes a connection ).Using this everything is working fine and CPU consumption of server has came down to 2%.But I have one issue in my mind.
As the definition of mutex says that consider if 10 threads are running and they are sharing a common resource suppose some global variables,so when one thread locks a mutex then other threads cannot access the shared resource until the thread which has locked the mutex releases it.Same will be the case with my application. consider I have 10 active threads 5 threads will lock the mutex turn by turn and other 5 will release the mutex. If a thread has locked the mutex then other 4 threads need to wait until it has been released. so at some point of time a deadlock condition might occur if a thread locks a mutex and it didn't get released then all other threads will keep waiting.
please help me get out of this issue.Being Theoretical it might look awkward but it is a real case scenario.Please go through the question again before giving a downvote.