File: rdwr.c

package info (click to toggle)
ganglia-monitor-core 2.5.7-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,300 kB
  • ctags: 3,900
  • sloc: ansic: 27,889; sh: 8,492; makefile: 148
file content (89 lines) | stat: -rw-r--r-- 2,057 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/********************************************************
 * An example source module to accompany...
 *
 * "Using POSIX Threads: Programming with Pthreads"
 *     by Brad nichols, Dick Buttlar, Jackie Farrell
 *     O'Reilly & Associates, Inc.
 *
 ********************************************************
 * rdwr.c --
 * 
 * Library of functions implementing reader/writer locks
 */
#include <pthread.h>
#include <ganglia/rdwr.h>

int
pthread_rdwr_init_np (pthread_rdwr_t * rdwrp)
{
  rdwrp->readers_reading = 0;
  rdwrp->writer_writing = 0;
  pthread_mutex_init (&(rdwrp->mutex), NULL);
  pthread_cond_init (&(rdwrp->lock_free), NULL);
  return 0;
}

int
pthread_rdwr_rlock_np (pthread_rdwr_t * rdwrp)
{
  pthread_mutex_lock (&(rdwrp->mutex));
  while (rdwrp->writer_writing)
    {
      pthread_cond_wait (&(rdwrp->lock_free), &(rdwrp->mutex));
    }
  rdwrp->readers_reading++;
  pthread_mutex_unlock (&(rdwrp->mutex));
  return 0;
}

int
pthread_rdwr_runlock_np (pthread_rdwr_t * rdwrp)
{
  pthread_mutex_lock (&(rdwrp->mutex));
  if (rdwrp->readers_reading == 0)
    {
      pthread_mutex_unlock (&(rdwrp->mutex));
      return -1;
    }
  else
    {
      rdwrp->readers_reading--;
      if (rdwrp->readers_reading == 0)
         {
	         pthread_cond_signal (&(rdwrp->lock_free));
         }
      pthread_mutex_unlock (&(rdwrp->mutex));
      return 0;
    }
}

int
pthread_rdwr_wlock_np (pthread_rdwr_t * rdwrp)
{
  pthread_mutex_lock (&(rdwrp->mutex));
  while (rdwrp->writer_writing || rdwrp->readers_reading)
    {
      pthread_cond_wait (&(rdwrp->lock_free), &(rdwrp->mutex));
    }
  rdwrp->writer_writing++;
  pthread_mutex_unlock (&(rdwrp->mutex));
  return 0;
}

int
pthread_rdwr_wunlock_np (pthread_rdwr_t * rdwrp)
{
  pthread_mutex_lock (&(rdwrp->mutex));
  if (rdwrp->writer_writing == 0)
    {
      pthread_mutex_unlock (&(rdwrp->mutex));
      return -1;
    }
  else
    {
      rdwrp->writer_writing = 0;
      pthread_cond_broadcast (&(rdwrp->lock_free));
      pthread_mutex_unlock (&(rdwrp->mutex));
      return 0;
    }
}