我想做一些線程化的基類。我編寫了代碼,我認爲它應該可以工作,編譯並運行,但不會顯示任何內容。我認爲,問題在於回調,但我可能是錯的。那麼,我的代碼有什麼問題?螺紋基類C++
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;
}
當你說「不顯示任何東西」,你的意思是不顯示命令提示符(或任何你運行該程序)還是僅僅意味着它不顯示任何文本? – KABoissonneault
它不顯示(std :: cout <<「Task \ n」;): 任務 任務 .... – user2123079