The Pedigree Project  0.1
Semaphore.h
1 /*
2  * Copyright (c) 2008-2014, Pedigree Developers
3  *
4  * Please see the CONTRIB file in the root of the source tree for a full
5  * list of contributors.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #ifndef SEMAPHORE_H
21 #define SEMAPHORE_H
22 
23 #include "pedigree/kernel/Atomic.h"
24 #include "pedigree/kernel/Spinlock.h"
25 #include "pedigree/kernel/compiler.h"
26 #include "pedigree/kernel/process/Event.h"
27 #include "pedigree/kernel/processor/types.h"
28 #include "pedigree/kernel/utilities/List.h"
29 #include "pedigree/kernel/utilities/Result.h"
30 #include "pedigree/kernel/utilities/new"
31 
36 {
37  public:
38  enum SemaphoreError
39  {
40  TimedOut,
41  Interrupted,
42  };
48  Semaphore(size_t nInitialValue, bool canInterrupt = true);
50  virtual ~Semaphore();
51 
58  SemaphoreResult acquireWithResult(
59  size_t n = 1, size_t timeoutSecs = 0, size_t timeoutUsecs = 0);
60 
62  bool acquire(size_t n = 1, size_t timeoutSecs = 0, size_t timeoutUsecs = 0)
63  {
64  SemaphoreResult result =
65  acquireWithResult(n, timeoutSecs, timeoutUsecs);
66  if (result.hasValue())
67  {
68  return result.value();
69  }
70  else
71  {
72  return false;
73  }
74  }
75 
79  bool tryAcquire(size_t n = 1);
80 
83  void release(size_t n = 1);
84 
86  ssize_t getValue();
87 
88  private:
91  Semaphore(const Semaphore &);
94  void operator=(const Semaphore &);
95 
97  void removeThread(class Thread *pThread);
98 
101  class SemaphoreEvent : public Event
102  {
103  public:
104  SemaphoreEvent();
105  virtual ~SemaphoreEvent();
106  virtual size_t serialize(uint8_t *pBuffer);
107  static bool unserialize(uint8_t *pBuffer, SemaphoreEvent &event);
108  virtual size_t getNumber();
109  };
110 
111  size_t magic;
112 
113  Atomic<ssize_t> m_Counter;
114  Spinlock m_BeingModified;
115  List<class Thread *> m_Queue;
116  bool m_bCanInterrupt;
117 };
118 
119 #endif
bool acquire(size_t n=1, size_t timeoutSecs=0, size_t timeoutUsecs=0)
Definition: Semaphore.h:62
Definition: Result.h:36
Definition: Thread.h:54
Definition: Event.h:48