feat/support_fiber #6

Merged
tqcq merged 52 commits from feat/support_fiber into master 2024-08-11 13:03:04 +08:00
Showing only changes of commit b5541c581c - Show all commits

View File

@ -10,6 +10,7 @@
namespace tile { namespace tile {
class CondVarTest : public ::testing::Test { class CondVarTest : public ::testing::Test {
protected:
void SetUp() override { void SetUp() override {
m = new Mutex(); m = new Mutex();
cv = new CondVar(); cv = new CondVar();
@ -18,24 +19,39 @@ class CondVarTest : public ::testing::Test {
} }
void TearDown() override { void TearDown() override {
SetWorker(nullptr);
delete m;
delete cv;
}
void SetWorker(std::thread *new_worker) {
if (worker) { if (worker) {
if (worker->joinable()) { if (worker->joinable()) {
worker->join(); worker->join();
} }
delete worker; delete worker;
} }
delete m; worker = new_worker;
delete cv;
} }
void ResetEnv() { void ResetEnv() {
is_started = false;
is_set = false; is_set = false;
is_timeout = false; is_timeout = false;
} }
void SetStarted() { is_started = true; }
void WaitStarted() {
while (!is_started) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
protected: protected:
Mutex *m; Mutex *m;
CondVar *cv; CondVar *cv;
bool is_started;
bool is_set; bool is_set;
bool is_timeout; bool is_timeout;
std::thread *worker; std::thread *worker;
@ -73,6 +89,7 @@ TEST_F(CondVarTest, NotifyOne_WaitFor) {
constexpr auto kWaitTimeout = std::chrono::milliseconds(50); constexpr auto kWaitTimeout = std::chrono::milliseconds(50);
auto WaitFor = [&] { auto WaitFor = [&] {
UniqueLock<Mutex> inner_locker(*m); UniqueLock<Mutex> inner_locker(*m);
SetStarted();
if (cv->WaitFor(inner_locker, kWaitTimeout)) { if (cv->WaitFor(inner_locker, kWaitTimeout)) {
is_set = true; is_set = true;
cv->NotifyOne(); cv->NotifyOne();
@ -80,10 +97,11 @@ TEST_F(CondVarTest, NotifyOne_WaitFor) {
is_timeout = true; is_timeout = true;
} }
}; };
{ {
std::thread t1(WaitFor); SetWorker(new std::thread(WaitFor));
WaitStarted();
std::this_thread::sleep_for(kWaitTimeout / 2); std::this_thread::sleep_for(kWaitTimeout / 2);
ASSERT_FALSE(is_set); ASSERT_FALSE(is_set);
@ -93,7 +111,7 @@ TEST_F(CondVarTest, NotifyOne_WaitFor) {
} }
auto now = ReadSteadyClock(); auto now = ReadSteadyClock();
t1.join(); worker->join();
if (now - start > kWaitTimeout) { if (now - start > kWaitTimeout) {
// timeout // timeout
ASSERT_TRUE(is_timeout); ASSERT_TRUE(is_timeout);
@ -106,18 +124,15 @@ TEST_F(CondVarTest, NotifyOne_WaitFor) {
// timeout // timeout
{ {
std::thread t1(WaitFor); ResetEnv();
SetWorker(new std::thread(WaitFor));
{ {
UniqueLock<Mutex> locker(*m); UniqueLock<Mutex> locker(*m);
ASSERT_FALSE(is_timeout); ASSERT_FALSE(is_timeout);
std::this_thread::sleep_for(kWaitTimeout);
ASSERT_FALSE(is_timeout);
cv->NotifyOne();
} }
worker->join();
t1.join();
ASSERT_TRUE(is_timeout); ASSERT_TRUE(is_timeout);
ASSERT_FALSE(is_set);
} }
} }