aboutsummaryrefslogtreecommitdiffstats
path: root/meowpp/meow/threading/thread_test.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'meowpp/meow/threading/thread_test.cpp')
-rw-r--r--meowpp/meow/threading/thread_test.cpp96
1 files changed, 96 insertions, 0 deletions
diff --git a/meowpp/meow/threading/thread_test.cpp b/meowpp/meow/threading/thread_test.cpp
new file mode 100644
index 0000000..7cb813e
--- /dev/null
+++ b/meowpp/meow/threading/thread_test.cpp
@@ -0,0 +1,96 @@
+#include <meow/threading/thread.h>
+#include <meow/syntax.h>
+
+#include <cstdint>
+#include <ctime>
+#include <vector>
+#include <algorithm>
+
+class WriteIntThread : public meow::Thread {
+ private:
+ int* ptr_;
+ double total_;
+
+ protected:
+ virtual double GetWaitingSeconds() = 0;
+
+ void Run() {
+ for (int i = 1, num = total_ / GetWaitingSeconds(); i <= num; i += 1) {
+ (*ptr_) += 1;
+ SleepSeconds(GetWaitingSeconds());
+ }
+ }
+
+ WriteIntThread(int* ptr, double total) : ptr_(ptr), total_(total) {}
+ public:
+};
+
+class TestThread_1 : public WriteIntThread {
+ protected:
+ double GetWaitingSeconds() { return 0.1; }
+
+ public:
+ TestThread_1(int* ptr, double total) : WriteIntThread(ptr, total) {}
+};
+
+class TestThread_10 : public WriteIntThread {
+ protected:
+ double GetWaitingSeconds() { return 1; }
+
+ public:
+ TestThread_10(int* ptr, double total) : WriteIntThread(ptr, total) {}
+};
+
+
+class JoinTimeTest : public meow::Thread {
+ private:
+ meow::Thread* ptr_;
+ bool ok_, can_check_;
+ double time_sec_, eps_;
+ protected:
+ void Run() {
+ std::chrono::system_clock::time_point ti1 = std::chrono::system_clock::now();
+ ptr_->Join();
+ std::chrono::system_clock::time_point ti2 = std::chrono::system_clock::now();
+ long int dur = std::chrono::duration_cast<std::chrono::microseconds>
+ (ti2 - ti1).count();
+ printf("%f %f\n", time_sec_, dur / 1e6);
+ ok_ = fabs(time_sec_ - 1.0 * dur / 1e6) < eps_;
+ can_check_ = true;
+ }
+ public:
+ JoinTimeTest(meow::Thread* ptr, double time_sec, double eps) {
+ ptr_ = ptr;
+ time_sec_ = time_sec;
+ eps_ = eps;
+ }
+ bool can_check() { return can_check_; }
+ bool ok() { return ok_; }
+};
+
+class Main {
+ public:
+ Main() {
+ int value1 = 0, value2 = 0;
+ double period = 5;
+ TestThread_1 t1(&value1, period);
+ TestThread_10 t2(&value2, period);
+ JoinTimeTest jt(&t1, period, 0.3);
+
+ t1.Start();
+ t2.Start();
+ jt.Start();
+ Assert(t1.id() != t2.id(), "t1/t2.id should not be same.");
+ Assert(t1.id() == t1.id(), "t1/t1.id should be same.");
+ Assert(t2.joinable(), "t2 should be joinable before detach");
+ t2.Detach();
+ Assert(!t2.joinable(), "t2 should not be joinable after detach");
+ jt.Join();
+ Assert(!t1.joinable(), "t2 should not be joinable after joined");
+ Assert(jt.ok(), "Join time failure...");
+ Assert(fabs(1.0 * value1 / value2 - 10) < 0.001, "10 times??");
+ exit(0);
+ };
+} _;
+
+int main() { return 0; }