I have 10 threads and 4 mutex variables. Every thread tries to lock the mutex variables. If it's unlocked, let's say it locks it and sleeps for 3 seconds. If it is locked, it uses a conditional variable and waits for it to become unlocked (it becomes unlocked when other thread unlocks it).
That's the way it should work: first, threads 0,1,2,3 lock the mutex variables. All of them sleep for 3 seconds, and unlock the mutex variables. After this,
another 4 threads should lock the mutex variables and sleep for 3 seconds. And so on, let's say it should last for ever (but it isn't so).
That's the way it works now: first, threads 0,1,2,3 lock the mutex variables. All of them sleep for 3 seconds, and unlock the mutex variables. After this, the same threads 0,1,2,3 lock the mutex variables. And so on, no other thread locks the mutex variables. It looks like there's something wrong with the conditional variable.
I will post some code now:
this function locks a mutex variable (tries to until it succeeds)
Code:
int
mutex_lock ()
{
int i;
while (1)
{
for (i = 0; i < nr_strunguri; i++)
if (pthread_mutex_trylock (&semm[i]) != EBUSY)
return i;
// daca nu mai e nici un strung liber
pthread_mutex_lock (&mutexc);
pthread_cond_wait (&cond, &mutexc);
pthread_mutex_unlock (&mutexc);
}
}
this function unlocks a mutex variable
Code:
int
mutex_unlock (int i)
{
pthread_mutex_unlock (&semm[i]);
pthread_cond_signal (&cond);
}
and this is the function of the thread:
Code:
void *
ocupa (char *sind)
{
int indm;
while (1)
{
indm = mutex_lock (); // returneaza numarul strungului care a fost ocupat
sleep (3);
mutex_unlock (indm);
}
}
PS: I apologize if you don't call them "mutex variable" and "conditional variable". I just translated word by word from my language. I think you can understand what I am talking about. Thank you.