aboutsummaryrefslogtreecommitdiffstats
path: root/meowpp/meow/threading/condition.h
diff options
context:
space:
mode:
Diffstat (limited to 'meowpp/meow/threading/condition.h')
-rw-r--r--meowpp/meow/threading/condition.h101
1 files changed, 101 insertions, 0 deletions
diff --git a/meowpp/meow/threading/condition.h b/meowpp/meow/threading/condition.h
new file mode 100644
index 0000000..5a03dfa
--- /dev/null
+++ b/meowpp/meow/threading/condition.h
@@ -0,0 +1,101 @@
+/*!
+ * @brief Contains a condition variable class.
+ * @author cathook
+ */
+#ifndef __MEOW_THREADING_CONDITION_H__
+#define __MEOW_THREADING_CONDITION_H__
+
+#include <meow/bases/object.h>
+#include <meow/threading/locks.h>
+#include <meow/bases/pointers.h>
+#include <meow/alloc.h>
+
+#include <condition_variable>
+#include <mutex>
+#include <chrono>
+
+namespace meow {
+
+
+namespace {
+
+/*!
+ * Condition in a anno-namespace.
+ */
+class AnnoCondition : public Object {
+ private:
+ //! MutexLock for the std::condition_variable
+ EntryPointer<MutexLock> plock_;
+
+ std::condition_variable cond_;
+
+ public:
+
+ /*!
+ * @brief Default constructor.
+ */
+ AnnoCondition() : AnnoCondition(EntryPointer<MutexLock>(EPCreateFlag)) {}
+
+ /*!
+ * @brief Constructs with a gived mutex lock.
+ * @param [in] plock The gived lock.
+ */
+ AnnoCondition(EntryPointer<MutexLock> const& plock) :
+ plock_(plock), cond_() {}
+
+ /*!
+ * @brief Acquires the lock.
+ */
+ void Acquire() {
+ plock_->Acquire();
+ }
+
+ /*!
+ * @brief Releases the lock.
+ */
+ void Release() {
+ plock_->Release();
+ }
+
+ /*!
+ * @brief Notifies one.
+ */
+ void NotifyOne() {
+ cond_.notify_one();
+ }
+
+ /*!
+ * @brief Notifies all.
+ */
+ void NotifyAll() {
+ cond_.notify_all();
+ }
+
+ /*!
+ * @brief Blocking wait.
+ */
+ void Wait() {
+ std::unique_lock<std::mutex> tmp(plock_->lock(), std::defer_lock);
+ cond_.wait(tmp);
+ }
+
+ /*!
+ * @brief Blocking wait with specified timeout.
+ * @param [in] timeout Timeout in seconds.
+ */
+ void WaitSeconds(double timeout) {
+ std::unique_lock<std::mutex> tmp(plock_->lock(), std::defer_lock);
+ cond_.wait_for(tmp, std::chrono::duration<double>(timeout));
+ }
+};
+
+}
+
+/*!
+ * @brief Condition varaible, detail see the AnnoCondition.
+ */
+typedef AnnoCondition Condition;
+
+}
+
+#endif // __MEOW_THREADING_CONDITION_H__