summaryrefslogtreecommitdiff
path: root/test/semaphore.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'test/semaphore.cpp')
-rw-r--r--test/semaphore.cpp37
1 files changed, 37 insertions, 0 deletions
diff --git a/test/semaphore.cpp b/test/semaphore.cpp
new file mode 100644
index 0000000..09124ee
--- /dev/null
+++ b/test/semaphore.cpp
@@ -0,0 +1,37 @@
+#include "semaphore.h"
+
+#ifndef __cpp_lib_semaphore
+# include <thread>
+
+semaphore::semaphore(unsigned int v_) : v {v_} { }
+
+void
+semaphore::release(unsigned int n)
+{
+ std::lock_guard lk {m};
+ v += n;
+}
+
+void
+semaphore::acquire()
+{
+ while (!try_dec()) { }
+}
+
+bool
+semaphore::try_dec()
+{
+ std::lock_guard lk {m};
+ if (v) {
+ v--;
+ m.unlock();
+ return true;
+ }
+ else {
+ m.unlock();
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ return false;
+ }
+}
+
+#endif