2015-06-25 104 views
0

我想做一些線程化的基類。我編寫了代碼,我認爲它應該可以工作,編譯並運行,但不會顯示任何內容。我認爲,問題在於回調,但我可能是錯的。那麼,我的代碼有什麼問題?螺紋基類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; 
} 
+0

當你說「不顯示任何東西」,你的意思是不顯示命令提示符(或任何你運行該程序)還是僅僅意味着它不顯示任何文本? – KABoissonneault

+0

它不顯示(std :: cout <<「Task \ n」;): 任務 任務 .... – user2123079

回答

4

您需要添加:

m_running = true; 

前:

m_thread = std::thread(&ThreadedBase::run, this); 
+0

是的,問題在於此。但現在它崩潰與「純虛函數調用」 – user2123079

+1

嘗試添加「覆蓋」關鍵字測試:: threadedBlock的聲明,以確保您正確覆蓋函數。 – KABoissonneault

+3

您從基類構造函數開始調用,派生對象不存在。從基礎構造函數中刪除if(start)this-> start()並將其添加到派生類。 –

1

你永遠不會沖洗std :: cout流。 嘗試改變:

std::cout << "Task\n"; 

std::cout << "Task" << std::endl; 

或者在線程的代碼某處調用std::cout.flush();

+0

謝謝,但這不是問題:) – user2123079

+0

它應該/可能是一個問題,我認爲。它可以在你的平臺上工作,但不適用於其他人 – KABoissonneault