我想做一些线程基类。我编写了代码,我认为应该可以工作,编译并运行,但它不会显示任何内容。我认为,问题在于回调,但我可能是错的。那么,我的代码有什么问题?
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;
}
答案 0 :(得分:4)
您需要添加:
m_running = true;
之前:
m_thread = std::thread(&ThreadedBase::run, this);
答案 1 :(得分:1)
你永远不会刷新std :: cout流。 尝试更改:
std::cout << "Task\n";
到
std::cout << "Task" << std::endl;
或者在线程代码中的某处调用std::cout.flush();
。