Subversion Repositories shark

Rev

Rev 2 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 pj 1
 
2
#include <fs/mutex.h>
3
#include <fs/semaph.h>
4
#include "mutex.h"
5
#include "rwlock.h"
6
 
7
void __rwlock_init(__rwlock_t *ptr)
8
{
9
  __mutex_init(&ptr->mutex,fsmutexattr);
10
  __sem_init(&ptr->readers_semaph,0);
11
  __sem_init(&ptr->writers_semaph,0);
12
  ptr->active_readers=0;
13
  ptr->active_writers=0;
14
  ptr->blocked_readers=0;
15
  ptr->blocked_writers=0;  
16
}
17
 
18
void __rwlock_rdlock(__rwlock_t *ptr)
19
{
20
  __mutex_lock(&ptr->mutex);
21
 
22
  if (ptr->active_writers==0&&ptr->blocked_writers==0) {
23
    ptr->active_readers++;
24
    __sem_signal(&ptr->readers_semaph);
25
  } else
26
    ptr->blocked_readers++;
27
 
28
  __mutex_unlock(&ptr->mutex);
29
 
30
  __sem_wait(&ptr->readers_semaph);
31
}
32
 
33
int __rwlock_tryrdlock(__rwlock_t *ptr)
34
{
35
  int ret;
36
 
37
  __mutex_lock(&ptr->mutex);
38
 
39
  ret=0;
40
  if (ptr->active_writers==0&&ptr->blocked_writers==0) {
41
    ptr->active_readers++;
42
    __sem_signal(&ptr->readers_semaph);
43
  } else
44
    ret=-1;
45
 
46
  __mutex_unlock(&ptr->mutex);
47
 
48
  if (ret==0) __sem_wait(&ptr->readers_semaph);
49
  return ret;
50
}
51
 
52
void __rwlock_wrlock(__rwlock_t *ptr)
53
{
54
  __mutex_lock(&ptr->mutex);
55
 
56
  if (ptr->active_readers==0&&ptr->active_writers==0) {
57
    ptr->active_writers=1;
58
    __sem_signal(&ptr->writers_semaph);
59
  }
60
  else
61
    ptr->blocked_writers++;
62
 
63
  __mutex_unlock(&ptr->mutex);
64
 
65
  __sem_wait(&ptr->writers_semaph);
66
}
67
 
68
int __rwlock_trywrlock(__rwlock_t *ptr)
69
{
70
  int ret;
71
 
72
  __mutex_lock(&ptr->mutex);
73
 
74
  ret=0;
75
  if (ptr->active_readers==0&&ptr->active_writers==0) {
76
    ptr->active_writers=1;
77
    __sem_signal(&ptr->writers_semaph);
78
  }
79
  else
80
    ret=-1;
81
 
82
  __mutex_unlock(&ptr->mutex);
83
 
84
  if (ret==0) __sem_wait(&ptr->writers_semaph);
85
  return ret;
86
}
87
 
88
void __rwlock_rdunlock(__rwlock_t *ptr)
89
{
90
  __mutex_lock(&ptr->mutex);
91
 
92
  ptr->active_readers--;
93
  if (ptr->active_readers==0&&ptr->blocked_writers>0) {
94
    ptr->active_writers=1;
95
    ptr->blocked_writers--;
96
    __sem_signal(&ptr->writers_semaph);
97
  }
98
 
99
  __mutex_unlock(&ptr->mutex);
100
}
101
 
102
void __rwlock_wrunlock(__rwlock_t *ptr)
103
{
104
  __mutex_lock(&ptr->mutex);
105
 
106
  ptr->active_writers=0;
107
  if (ptr->blocked_readers>0) {
108
    do {
109
      ptr->blocked_readers--;
110
      ptr->active_readers++;
111
      __sem_signal(&ptr->readers_semaph);
112
    } while(ptr->blocked_readers!=0);
113
  } else if (ptr->blocked_writers>0) {
114
    ptr->active_writers=1;
115
    ptr->blocked_writers--;
116
    __sem_signal(&ptr->writers_semaph);
117
  }
118
 
119
  __mutex_unlock(&ptr->mutex);
120
}