I have an assignment on where I need to do some thread management. The problem is that I'm only allowed to use one mutex, nothing more, no more conditions or anything else.
I have a struct which contains some data which 2 threads change and a mutex. The struct is arranged in an array and is accessed via the index.
EDIT: I think this is a better explanation. The problem is that I have a deadlock because thread2 still holds a lock and thread1 wants to acquire it, or sometimes the opposite.
typedef struct {
int number;
pthread_mutex_t mutex;
} data;
data myStruct[100];
void* thread1()
{
pthread_mutex_lock(&myStruct[index].mutex)
// get 1 index value
// access the struct via index
// change a value
pthread_mutex_unlock(&myStruct[index].mutex)
}
void* thread2()
{
pthread_mutex_lock(&myStruct[index1].mutex)
pthread_mutex_lock(&myStruct[index2].mutex)
// get 2 index values
// access struct with both indexes
// change values with both indexes
pthread_mutex_unlock(&myStruct[index2].mutex)
pthread_mutex_unlock(&myStruct[index1].mutex)
}
The index values are obtained via some random calculations. Mutex initialisation and destruction, and thread creation are not in my hands.
I have 2 threads. Both threads can access the struct and the mutex within. and have to use this mutex to lock and unlock the data. Thread 1 only changes data from one data struct, thread 2 changes data from two data structs.
The problem is that I have to wait for mutexes in both threads, and at the moment I solved it via
while(pthread_mutex_lock(&struct[i].lock) != 0)
It works sometimes, but I have no better idea how I should do this locking only with this single mutex. I'm not allowed to make more mutexes, semaphores or conditions.
Do you have any ideas what I could try?