threads and monitor
This commit is contained in:
72
src/Core/testing/ThreadsTest.cpp
Normal file
72
src/Core/testing/ThreadsTest.cpp
Normal file
@@ -0,0 +1,72 @@
|
||||
#include "Core/Threads.h"
|
||||
#include <iostream>
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
|
||||
using namespace uLib;
|
||||
|
||||
class MyThread : public Thread {
|
||||
public:
|
||||
MyThread() : counter(0) {}
|
||||
void Run() override {
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
counter++;
|
||||
Thread::Sleep(10);
|
||||
}
|
||||
}
|
||||
std::atomic<int> counter;
|
||||
};
|
||||
|
||||
void TestBasicThread() {
|
||||
std::cout << "Testing basic Thread lifecycle..." << std::endl;
|
||||
MyThread t;
|
||||
assert(!t.IsRunning());
|
||||
t.Start();
|
||||
assert(t.IsRunning());
|
||||
t.Join();
|
||||
assert(!t.IsRunning());
|
||||
assert(t.counter == 5);
|
||||
std::cout << " Passed." << std::endl;
|
||||
}
|
||||
|
||||
void TestThreadDetach() {
|
||||
std::cout << "Testing Thread Detach..." << std::endl;
|
||||
std::atomic<bool> done(false);
|
||||
|
||||
// Using a lambda or a simple subclass
|
||||
class DetachedThread : public Thread {
|
||||
public:
|
||||
DetachedThread(std::atomic<bool>& d) : m_done(d) {}
|
||||
void Run() override {
|
||||
Thread::Sleep(50);
|
||||
m_done = true;
|
||||
}
|
||||
std::atomic<bool>& m_done;
|
||||
};
|
||||
|
||||
{
|
||||
DetachedThread* t = new DetachedThread(done);
|
||||
t->Start();
|
||||
t->Detach();
|
||||
// The thread object 't' is still alive here,
|
||||
// but it will be destroyed soon if we delete it.
|
||||
// For a detached thread using members, we MUST keep it alive.
|
||||
|
||||
int wait_count = 0;
|
||||
while(!done && wait_count < 20) {
|
||||
Thread::Sleep(10);
|
||||
wait_count++;
|
||||
}
|
||||
delete t;
|
||||
}
|
||||
|
||||
assert(done);
|
||||
std::cout << " Passed." << std::endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
TestBasicThread();
|
||||
TestThreadDetach();
|
||||
std::cout << "All Thread tests passed!" << std::endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user