2013-08-22 59 views
6

我試圖編寫一個命令行服務器,它將從串行端口接收信息,解析它,並將其記錄在內部對象中。C++ std ::成員函數的線程

然後根據客戶端的請求,服務器將返回請求的信息。

我想要做的是將接收器&分析器部件放在一個單獨的線程中,以便讓服務器沿着一側運行,而不會干擾數據收集。

#include <iostream> 
#include <thread> 

class exampleClass{ 
    std::thread *processThread; 

    public void completeProcess(){ 
     while(1){ 
      processStep1(); 
      if (verification()){processStep2()} 
     } 
    }; 

    void processStep1(){...}; 
    void processStep2(){...}; 
    bool verification(){...}; 
    void runThreaded(); 
} // End example class definition 

// The idea being that this thread runs independently 
// until I call the object's destructor 

exampleClass::runThreaded(){ 
    std::thread processThread(&exampleClass::completeProcess, this); 
} // Unfortunately The program ends up crashing here with CIGARET 
+0

是否可以編譯public void completeProcess(){..'? – Deqing

+0

可能重複[啓動線程與成員函數](http://stackoverflow.com/questions/10673585/start-thread-with-member-function) –

回答

8

您正在運行一個成員函數內部本地線程。你必須加入它或分離它,由於它是本地的,你必須要做到這一點在函數中:

exampleClass::runThreaded() 
{ 
    std::thread processThread(&exampleClass::completeProcess, this); 
    // more stuff 
    processThread.join(); 
} // 

我猜你真正想要的是推出一個數據成員線程,而不是推出的本地的。如果你這樣做,你仍然需要在某個地方加入它,例如在析構函數中。在這種情況下,你的方法應該是

exampleClass::runThreaded() 
{ 
    processThread = std::thread(&exampleClass::completeProcess, this); 
} 

和析構函數

exampleClass::~exampleClass() 
{ 
    processThread.join(); 
} 

processThread應該是一個std::thread,而不是一個指針之一。

只是設計上的一個注意事項:如果要在線程數據成員上使用runThreaded方法,則必須非常小心在線程加入之前不要多次調用它。在構造函數中啓動線程並將其加入到析構函數中可能更有意義。

+0

這(第二個想法)是它,謝謝! – Torrijos

3

線程對象在堆棧上,它將在函數結束時被破壞。線程對象析構函數調用std::terminate如果線程仍在運行,就像你的情況一樣。見here