Hello all,
I'm working on a small wrapper library for a bigger project, and i've been killing my self over (what I think is) a pointer problem.
Here is the code (I extracted the part of the code where the problem is for better reading, I tested the code below, and I get the same problem):
wrapper.c
#include <stdio.h>
#include <pthread.h>
#include "rwmutex.h"
rwmutex_t* create_rwmutex()
{
rwmutex_t m;
pthread_mutex_init(&m.rm, NULL);
pthread_mutex_init(&m.wm, NULL);
pthread_cond_init(&m.rc, NULL);
return &m;
}
void write_lock(rwmutex_t *m)
{
pthread_mutex_lock(&m->wm);
}
void write_unlock(rwmutex_t *m)
{
pthread_mutex_unlock(&m->wm);
}
wrapper.h
typedef struct
{
pthread_mutex_t wm; //write mutex
pthread_mutex_t rm; //read mutex
pthread_cond_t rc; //read condition var
} rwmutex_t;
rwmutex_t* create_rwmutex ();
void write_lock (rwmutex_t *m);
void write_unlock (rwmutex_t *m);
tester.c
#include <stdio.h>
#include <pthread.h>
#include "rwmutex.h"
void* f1(void* p);
rwmutex_t *m;
pthread_t t1, t2;
int main(int argc, char* argv[])
{
m = create_rwmutex();
pthread_create(&t1, NULL, f1, 4);
sleep(1);
pthread_create(&t2, NULL, f1, 5);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
void* f1(void* p)
{
int i = (int)p;
write_lock(m);
printf("[%d] WRITE IN\n", i);
sleep(2);
printf("[%d] WRITE OUT\n", i);
write_unlock(m);
}
After compiling with 'gcc wrapper.c tester.c -o t -lpthread' .. I get some warnings.
When I execute './t' I get the output:
[4] WRITE IN
[5] WRITE IN
[4] WRITE OUT
[5] WRITE OUT
What I should get is a synchronized output, that is, the second thread waits for the first thread to complete, so the output should be:
[4] WRITE IN
[4] WRITE OUT
[5] WRITE IN
[5] WRITE OUT
I'm running this on a Windows environment using Cygwin.
Thanks in advance for your time,
Naimi


