2014-06-26 31 views
0

我嘗試記住線程是如何工作的,我發現使用C++11可以簡化它的創建和使用。我使用這個職位Simple example of threading in C++的答案來創建一個簡單的線程。創建線程時出現簡單錯誤

但是,我和帖子的答案之間存在差異,我不在main中,所以我在構造函數中創建我的線程,並且它不是相同的參數。

這裏是我的簡單的代碼和我嘗試做:

我在一類mainWindow.cpp

//Constructor 
MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 
    // Constructs the new thread and runs it. Does not block execution. 
    thread t1(lancerServeur, NULL); 
    ui->setupUi(this); 
} 
void MainWindow::lancerServeur(){ 
    std::cout << "Le serveur se lance"; 
} 

的錯誤是:

expected ';' before 't1' 

statement cannot resolve address of overloaded function thread t1(lancerServeur, NULL); 

我想我的參數thread t1(lancerServeur, NULL);是錯誤的。

你能解釋一下它是如何工作的嗎?

謝謝。

回答

4

您使用std::cout,所以我假設using namespace std;thread之前的某個地方。嘗試std::thread

嘗試拉姆達std::thread t1([this](){this->lancerServeur();});

退出構造函數之前不要忘了th1.join(),否則std::terminate將在thread析構函數被調用。

如果th1線程將運行一段時間,然後使它成爲一個類的成員變量,然後初始化看起來像th1 = std::move(std::thread t1([this](){this->lancerServeur();}));在類的析構,th1.join();

+0

,當我在前面使用std我這有線程:沒有匹配的函數調用'std :: thread :: thread(,NULL)' –

+0

函數'MainWindow :: lancerServeur'應該是靜態的或使用lambda'std :: thread( [this](){this-> lancerServeur();});' – Niall

+0

如果我把它放在靜態我有這樣的:'class std :: result_of ' typedef typename result_of <_Callable(_Args ...)> :: type result_type; –