#pragma once
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <mutex>
#include <thread>
namespace teapot{
namespace base {
class TWait {
public:
virtual void NotifyOne() {}
virtual void BreakAllWait() {}
virtual bool EmptyWait() = 0;
virtual ~TWait() {}
};
class BlockTWait : public TWait {
public:
BlockTWait() {}
void NotifyOne() override { cv_.notify_one(); }
bool EmptyWait() override {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock);
return true;
}
void BreakAllWait() override { cv_.notify_all(); }
private:
std::mutex mutex_;
std::condition_variable cv_;
};
class SleepTWait : public TWait {
public:
SleepTWait() {}
explicit SleepTWait(uint64_t sleep_time_us)
: sleep_time_us_(sleep_time_us) {}
bool EmptyWait() override {
std::this_thread::sleep_for(std::chrono::microseconds(sleep_time_us_));
return true;
}
void SetSleepTimeMicroSeconds(uint64_t sleep_time_us) {
sleep_time_us_ = sleep_time_us;
}
private:
uint64_t sleep_time_us_ = 10000;
};
class YieldTWait : public TWait {
public:
YieldTWait() {}
bool EmptyWait() override {
std::this_thread::yield();
return true;
}
};
class BusySpinTWait : public TWait {
public:
BusySpinTWait() {}
bool EmptyWait() override { return true; }
};
class TimeoutBlockTWait : public TWait {
public:
TimeoutBlockTWait() {}
explicit TimeoutBlockTWait(uint64_t timeout)
: time_out_(std::chrono::milliseconds(timeout)) {}
void NotifyOne() override { cv_.notify_one(); }
bool EmptyWait() override {
std::unique_lock<std::mutex> lock(mutex_);
if (cv_.wait_for(lock, time_out_) == std::cv_status::timeout) {
return false;
}
return true;
}
void BreakAllWait() override { cv_.notify_all(); }
void SetTimeout(uint64_t timeout) {
time_out_ = std::chrono::milliseconds(timeout);
}
private:
std::mutex mutex_;
std::condition_variable cv_;
std::chrono::milliseconds time_out_;
};
} // namespace base
} // namespace teapot
测试代码
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include "wait.h"
using teapot::base::TWait;
using teapot::base::BlockTWait;
int main ()
{
int i = 0;
TWait *wait = new BlockTWait();
std::thread t1([wait](){
int id = 1;
std::cout << "Before wait thread #" << id << std::endl;
wait->EmptyWait();
std::cout << "After wait thread #" << id << std::endl;
});
std::thread t2([wait](){
int id = 2;
std::cout << "thread #" << id << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
wait->NotifyOne();
});
t1.join();
t2.join();
delete wait;
return 0;
}