I need to do proper synchronization over several threads in my application. The threads are devided into a group of threads - graup A which may contain more then one thread and thread B. Thread B is supposed to be unlocker thread while only one thread from group A at the same time is supposed to be unlocked by thread B. I tryied to achive stable solution using pthread_mutex_t with code like this:
// thread group A
...
while(...)
{
pthread_mutex_lock(&lock) ;
// only one thread at the same time allowed from here
...
}
// thread B
while(...)
{
pthread_mutex_unlock(&lock)
...
}
...
int main()
{
...
pthread_mutex_init(&lock, NULL) ;
pthread_mutex_lock(&lock) ;
...
// start threads
...
}
This solution works but is unstable and sometimes causes deadlock because if it happens that
pthread_mutex_unlock(&lock) ;
is called before
pthread_mutex_lock(&lock) ;
then mutex stays locked and causes deadlock because
pthread_mutex_unlock(&lock) ;
has no effect if it is called before
pthread_mutex_lock(&lock) ;
I found one crappy solution to this but it's crappy because it eats additional cpu time needlessly. Such solution is this:
bool lock_cond ;
// thread group A
...
while(...)
{
lock_cond = true ;
pthread_mutex_lock(&lock) ;
lock_cond = false ;
// only one thread at the same time allowed from here
...
}
// thread B
while(...)
{
while(!lock_cond)
;
pthread_mutex_unlock(&lock)
...
}
...
int main()
{
...
pthread_mutex_init(&lock, NULL) ;
pthread_mutex_lock(&lock) ;
...
// start threads
...
}
So my question is how to properly implement threads synchronization in such scenario ?. Can I use
pthread_mutex_t
variables for that or does I have to use semaphore ? Please explain with code examples.