I'm just messing around with mutex and rwlock in pthreads. I wrote a quick little sample. but what's interesting is that the rwlock behaves much differently.
Code:
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
int kill = 0;
char * s = NULL;
bool userw = false;
pthread_t tim;
pthread_t th1;
pthread_t th2;
pthread_mutex_t klock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t slock = PTHREAD_MUTEX_INITIALIZER;
pthread_rwlock_t slock2 = PTHREAD_RWLOCK_INITIALIZER;
void * thfn1(void * args) {
printf("thfn1\n");
bool ext = false;
while(1) {
pthread_mutex_lock(&klock);
if(kill == 1) ext = true;
pthread_mutex_unlock(&klock);
if(ext == true) break;
if(userw) pthread_rwlock_wrlock(&slock2);
else pthread_mutex_lock(&slock);
if(s) free(s);
s = strdup("bbb");
printf("%s\n",s);
sleep(arc4random() % 5);
printf("th1 awake\n");
if(userw) pthread_rwlock_unlock(&slock2);
else pthread_mutex_unlock(&slock);
}
printf("thread1 finished\n");
return NULL;
}
void * thfn2(void * args) {
printf("thfn2\n");
bool ext = false;
while(1) {
pthread_mutex_lock(&klock);
if(kill == 1) ext = true;
pthread_mutex_unlock(&klock);
if(ext == true) break;
if(userw) pthread_rwlock_wrlock(&slock2);
else pthread_mutex_lock(&slock);
if(s) free(s);
s = strdup("ccc");
printf("%s\n",s);
sleep(arc4random() % 5);
printf("th2 awake\n");
if(userw) pthread_rwlock_unlock(&slock2);
else pthread_mutex_unlock(&slock);
}
printf("thread 2 finished\n");
return NULL;
}
void * timfn(void * args) {
int activetime = *(int *)args;
sleep(activetime);
pthread_mutex_lock(&klock);
kill = 1;
pthread_mutex_unlock(&klock);
return NULL;
}
int main(int argc, char ** argv) {
int activetime = 45; //seconds
pthread_create(&th1,NULL,thfn1,NULL);
pthread_create(&th2,NULL,thfn2,NULL);
pthread_create(&tim,NULL,timfn,&activetime);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
pthread_join(tim,NULL);
return 0;
}
When this is run with read/write locks on, only the first thread ever acquires the write lock. But with read/write lock turned off, the threads will alternate access to the "s" variable. Note that it's not meant to be a 1to1 alternation.
Any ideas why the second thread never acquires the write lock?
Thanks!