So basically I am working on a class project where we make our own implementation of a lock. I am fairly certain my lock code is correct, however my testing code is not working properly. we are using a version of pthreads called sthreads that my professor gave to the class.
here is my testing code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "sync.h"
#include "sthread.h"
sthread_mutex_t *mutex;
int locktest(void* arg){
int threadNum = (int)arg;
//int i;
for(;;){
int x = sthread_mutex_lock(mutex);
printf("return value: %d\n", x);
//sleep(1);
printf("thread %d has the lock\n", threadNum);
sleep(1);
sthread_mutex_unlock(mutex);
}
return 0;
}
int main(){
sthread_t thr1, thr2, thr3, thr4, thr5;
if (sthread_init() == -1){
return -1;
}
if(sthread_mutex_init(mutex)){
return -1;
}
sthread_mutex_lock(mutex);
if (sthread_create(&thr1, locktest, (void *)1) == -1){
return -1;
}
if (sthread_create(&thr2, locktest, (void *)2) == -1){
return -1;
}
if (sthread_create(&thr3, locktest, (void *)3) == -1){
return -1;
}
if (sthread_create(&thr4, locktest, (void *)4) == -1){
return -1;
}
if (sthread_create(&thr5, locktest, (void *)5) == -1){
return -1;
}
sleep(100);
sthread_mutex_unlock(mutex);
sthread_mutex_destroy(mutex);
return 0;
}
I’ve descovered that for some reason, even though mutex is global, each thread has a different instance of it. I know this because the return value for each call to sthread_mutex_lock(mutex) in the function locktest (which each thread runs) is not 0. this indicates the lock has not been initialized and is thus a null pointer, even though you see I initialized it in main in the second if statement.
does anyone have any clue as to why this is happening?
You never initialize
mutexto point at anything, so it has the valueNULL.sthread_mutex_init(mutex)isn’t going to work, since it was basically passed the valueNULL.You probably want
sthread_mutex_init(&mutex)(declaresthread_mutex_initas taking asthread_mutex_t **).