xrootd
XrdSysSemWait.hh
Go to the documentation of this file.
1 #ifndef __SYS_SEMWAIT__
2 #define __SYS_SEMWAIT__
3 
4 /******************************************************************************/
5 /* X r d S y s S e m W a i t */
6 /* */
7 /* Author: Fabrizio Furano (INFN, 2005) */
8 /* */
9 /* A counting semaphore with timed out wait primitive */
10 /******************************************************************************/
11 
12 // $Id$
13 
14 #include "XrdSys/XrdSysPthread.hh"
15 
17  public:
18 
19  int CondWait() {
20 
21  int rc = 0;
22  // Wait until the sempahore value is positive. This will not be starvation
23  // free is the OS implements an unfair mutex;
24  // Returns 0 if signalled, non-0 if would block
25  //
26 
27  semVar.Lock();
28  if (semVal > 0) semVal--;
29  else {
30  rc = 1;
31  }
32 
33  semVar.UnLock();
34 
35  return rc;
36 
37  };
38 
39  void Post() {
40  // Add one to the semaphore counter. If we the value is > 0 and there is a
41  // thread waiting for the sempagore, signal it to get the semaphore.
42  //
43  semVar.Lock();
44 
45  if (semWait > 0) {
46  semVar.Signal();
47  semWait--;
48  }
49  else
50  semVal++;
51 
52  semVar.UnLock();
53  };
54 
55  void Wait() {
56  // Wait until the sempahore value is positive. This will not be starvation
57  // free is the OS implements an unfair mutex;
58  //
59 
60  semVar.Lock();
61  if (semVal > 0) semVal--;
62  else {
63  semWait++;
64  semVar.Wait();
65  }
66 
67  semVar.UnLock();
68 
69  };
70 
71  int Wait(int secs) {
72  int rc = 0;
73  // Wait until the sempahore value is positive. This will not be starvation
74  // free is the OS implements an unfair mutex;
75  // Returns 0 if signalled, non-0 if timeout
76  //
77 
78  semVar.Lock();
79  if (semVal > 0) semVal--;
80  else {
81  semWait++;
82  rc = semVar.Wait(secs);
83  if (rc) semWait--;
84  }
85 
86  semVar.UnLock();
87 
88  return rc;
89  };
90 
91  XrdSysSemWait(int semval=1,const char *cid=0) : semVar(0, cid) {
92  semVal = semval; semWait = 0;
93  }
94 
96 
97 private:
98 
100 int semVal;
102 };
103 
104 
105 
106 #endif