我想做一些线程基类。我编写了代码,我认为它应该可以工作,它编译并运行但它什么都不显示。我认为,问题出在回调中,但我可能是错的。那么,我的代码有什么问题?
class ThreadedBase
{
public:
ThreadedBase(bool start = false) : m_running(false) {
if (start)
this->start();
}
virtual ~ThreadedBase() {
m_running = false;
m_thread.join();
}
bool start(){
if (m_running) {
return false;
};
m_thread = std::thread(&ThreadedBase::run, this);
m_running = true;
return true;
};
bool stop(){
if (!m_running) {
return false;
};
m_running = false;
return true;
};
protected:
virtual void threadedBlock() = 0;
void run() {
while (m_running) {
threadedBlock();
}
}
private:
std::thread m_thread;
bool m_running;
};
class Test : public ThreadedBase
{
public:
Test(bool start = true) : ThreadedBase(start) {}
void threadedBlock() {
std::cout << "Task\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
};
int main()
{
Test t(true);
t.start();
std::this_thread::sleep_for(std::chrono::seconds(100));
return 0;
}
你需要添加:
m_running = true;
之前:
m_thread = std::thread(&ThreadedBase::run, this);
我是一名优秀的程序员,十分优秀!