#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#define MAGIC 1234
#define ERROR 1
#define SUCCESS 0
#define NUM 10
struct rwlock_t{
int r;//reader num
int w;//writer num
int r_wait;
int w_wait;
int magic;
pthread_mutex_t mutex;
pthread_cond_t r_cond;
pthread_cond_t w_cond;
};
void rwlock_init(struct rwlock_t *rwl)
{
rwl->r = 0;
rwl->w = 0;
rwl->r_wait = 0;
rwl->w_wait = 0;
rwl->magic = MAGIC;
pthread_mutex_init(&rwl->mutex,NULL);
pthread_cond_init(&rwl->r_cond,NULL);
pthread_cond_init(&rwl->w_cond,NULL);
}
struct rwlock_t rwl;
pthread_mutex_t lock;
int rwl_rdlock(struct rwlock_t *rwl)
{
int ret = 0;
if(rwl->magic != MAGIC)
{
return ERROR;
}
ret = pthread_mutex_lock(&rwl->mutex);
if(ret)
return ret;
if(rwl->w)
{
rwl->r_wait++;
pthread_cond_wait(&rwl->r_cond,&rwl->mutex);
rwl->r++;
rwl->r_wait--;
ret = pthread_mutex_unlock(&rwl->mutex);
return ret;
}
rwl->r++;
ret = pthread_mutex_unlock(&rwl->mutex);
return ret;
}
int rwl_wrlock(struct rwlock_t *rwl)
{
int ret = 0;
if(rwl->magic != MAGIC)
{
return ERROR;
}
ret = pthread_mutex_lock(&rwl->mutex);
if(ret)
return ret;
if(rwl->r > 0)
{
rwl->w_wait++;
pthread_cond_wait(&rwl->w_cond,&rwl->mutex);
rwl->w_wait--;
rwl->w = 1;
ret = pthread_mutex_unlock(&rwl->mutex);
return ret;
}
rwl->w = 1;
ret = pthread_mutex_unlock(&rwl->mutex);
return ret;
}
int rwl_unlock(struct rwlock_t *rwl)
{
int ret = 0;
if(rwl->magic != MAGIC)
{
return ERROR;
}
ret = pthread_mutex_lock(&rwl->mutex);
if(ret)
return ret;
if(rwl->r)
rwl->r--;
else
{
rwl->w = 0;
}
if(rwl->r == 0 && rwl->w_wait)
{
pthread_cond_signal(&rwl->w_cond);
}
if(rwl->w == 0 && rwl->r_wait)
{
pthread_cond_broadcast(&rwl->r_cond);
}
ret = pthread_mutex_unlock(&rwl->mutex);
return ret;
}
void *test_fun(void *arg)
{
int i = 0;
i = *(int *)arg;
pthread_mutex_unlock(&lock);
int ret = rwl_rdlock(&rwl);
if(0 == ret)
{
printf("i:%d get rdlock ok\n",i);
}
sleep(i);
ret = rwl_unlock(&rwl);
if(0 == ret)
{
printf("i:%d free rdlock ok\n",i);
}
}
void *test_fun1(void* arg)
{
int ret = rwl_wrlock(&rwl);
if(0 == ret)
{
printf("write get wrlock ok\n");
}
sleep(3);
ret = rwl_unlock(&rwl);
if(0 == ret)
{
printf("write free wrlock ok\n");
}
}
int main()
{
int i = 0;
pthread_t tid[NUM] = {0};
pthread_t w_tid = 0;
int err[NUM] = {0};
pthread_mutex_init(&lock,NULL);
rwlock_init(&rwl);
for(i=0;i<NUM;i++)
{
if(i == 0)
{
pthread_create(&w_tid,NULL,test_fun1,NULL);
}
pthread_mutex_lock(&lock);
err[i] = pthread_create(&tid[i],NULL,test_fun,&i);
if(err[i])
{
printf("pthread create error\n");
pthread_mutex_unlock(&lock);
}
}
for(i=0;i<NUM;i++)
{
if(0 == tid[i])
{
continue;
}
pthread_join(tid[i],NULL);
}
pthread_join(w_tid,NULL);
}
互斥锁和条件变量实现读写锁
最新推荐文章于 2021-08-17 22:27:48 发布